iOS 使用UITextField隐藏键盘

1、点击键盘return键,触发代码隐藏:

 (1)当前UIController实现UITextFieldDelegate:

@interface KingViewController :UIViewController <UITextFieldDelegate> {

...

}

(2) 添加textField,在XB中连接其delegate为KingViewController

(3) 在KingViewController.m中实现:

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {  // 这个方法是UITextFieldDelegate协议里面的

    NSLog(@"textFieldShouldReturn the keyboard *** %@ ",theTextField.text);

    if (theTextField == self.textField) {

        [theTextField resignFirstResponder]; //这句代码可以隐藏 键盘

    }

   returnYES;

}


2、当UITextField设置键盘为Number时,没有return键,无法使用上面的方法,就试试下面的方法:



 (1) 在xb中,选中背景的UIView,将其Custom Class由 UIView 修改为 UIControl

 (2) 在KingViewController.h中声明一个IBAction:

 (IBAction)clickBackground:(id)sender;

 (3) 在xb中连接这个IBAction和Background的UIControl, Touch Up inside

 (4) 在KingViewController.m中实现:

- (IBAction)clickBackground:(id)sender {

    NSLog(@"clickBackground enter *** ");

    int t = [self.mRootViewtag];

   if(t ==1001) {

        NSLog(@"you click background *** ");

        [sender endEditing:YES];  //这句代码可以 隐藏键盘

//[[[UIApplication sharedApplication] keyWindow] endEditing:YES];  //一样的效果


    }

}


3、跟2一样,可以实现点击空白处隐藏键盘:

 (1)xib中拖一个UIButton,将大小拖到最大,覆盖到整个界面

 (2)设置刚才的UIButton控件到最下面: Editor -> Arrangement ->send to Back


 

(3)同上面的2方法,设置UIButton的IBAction事件,并在IBAction事件中实现键盘隐藏:

在KingViewController.m中实现:

- (IBAction)clickBackground:(id)sender {

    NSLog(@"clickBackground enter *** ");

    int t = [self.mRootViewtag];

   if(t ==1001) {

        NSLog(@"you click background *** ");

[[[UIApplication sharedApplicationkeyWindowendEditing:YES];  //这句代码可以 隐藏键盘

    }

}




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值