zoukankan      html  css  js  c++  java
  • iOS点击键盘以外空白区域隐藏键盘的常见方法

    iOS开发中,经常要用到输入框,可默认情况下,输入框出来之后,除非点击键盘上面的“Done”或“Next”按钮才能将其隐藏。站在用户体验的角度上看,这种情况很不友好,尤其是不能突显苹果操作的便捷性。因此,查阅了一些资料,加上实践,总结出了两种方法:

    第一种,是最常见的,就是给最外层的view添加一个手势响应UITapGestureRecognizer,代码如下:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
        tapGr.cancelsTouchesInView = NO;
        [self.view addGestureRecognizer:tapGr];
    }
    
    -(void)viewTapped:(UITapGestureRecognizer*)tapGr
    {
        [activitySearchBar resignFirstResponder];
    }
    

    第二种,稍微复杂些,不过思路也差不多,就是将最外层的view作为一个UIScrollView,点击即可将当前的焦点交给UIScrollView,代码如下:

    #import <UIKit/UIKit.h>
    #import "BaseData.h"
    
    @interface BaseTextFieldView : UIScrollView {
    	id target;
    	int ypos,y;
    }
    -(void)setTarget:(id)d;
    
    @end
    

      

    #import "BaseTextFieldView.h"
    
    @implementation BaseTextFieldView
    
    - (id)initWithFrame:(CGRect)frame {
        
        self = [super initWithFrame:frame];
        if (self) {
            // Initialization code.
        }
        return self;
    }
    
    - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
    {
    	[target performSelector:@selector(endEdit)];
    	return YES;
    }
    
    -(void)setTarget:(id)d
    {
    	ypos = 0;
    	target = d;
    }
    
    -(BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view
    {
    	return YES;
    }
    
    - (void)dealloc {
        [super dealloc];
    }
    

     在需要调用的Controller的.h文件添加对UITextFieldDelegate的引用,代码如下:

    #import "BaseTextFieldView.h"
    

      

    @interface DemoController : UIViewController <UITextFieldDelegate>{
    	
    }
    

     将xib文件的view,改成对BaseTextFieldView的引用,如图:

        

    在Controller的.m文件中,添加代码:

    [(BaseTextFieldView *)self.view setTarget:self];
    

      

    以上两种方法经测试均可实现。

     

  • 相关阅读:
    hihoCoder #1176 : 欧拉路·一 (简单)
    228 Summary Ranges 汇总区间
    227 Basic Calculator II 基本计算器II
    226 Invert Binary Tree 翻转二叉树
    225 Implement Stack using Queues 队列实现栈
    224 Basic Calculator 基本计算器
    223 Rectangle Area 矩形面积
    222 Count Complete Tree Nodes 完全二叉树的节点个数
    221 Maximal Square 最大正方形
    220 Contains Duplicate III 存在重复 III
  • 原文地址:https://www.cnblogs.com/jaenson/p/iOS_Keybroad_Hide.html
Copyright © 2011-2022 走看看