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];

  

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

posted @ 2015-03-23 22:35  天使的翅膀——  阅读(481)  评论(0编辑  收藏  举报