键盘消失方法一:Delegate应用三步法
一、遵循:遵循代理协议,ViewController要遵循<UITextFieldDelegate>协议。
二、调用:调用代理的方法,在“textFieldShouldReturn:”中调用resignFirstResponder。
三、关联:关联委托者与被委托者,将UITextField对象的Delegate指派给该对象所在的ViewController。
第一步:在ViewController.h文件中,添加以下代码:
@interface ViewController : UIViewController <UITextFieldDelegate>
第二步:释放第一响应者resignFirstResponder。在ViewController.m文件中,添加以下代码:
#pragma mark - - uiTextFieldDelegate
-(BOOL) textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
第三步:关联委托者与被委托者。在Storyboard中,完成委托者与被委托者的关联,可谓弹指一间。
具体操作是,选中视图中的TextField控件,通过“Ctrl+drag”操作,引向Dock中的ViewController,从弹出框中,选择Delegate。
键盘消失方法之二:将UIView改为UIControl
第一步:将UIView改为UIControl
单击Document Outline中的View,在右侧的Identity Inspector中可看到,该View默认的Custom Class 是 UIView。
此时,查看它的connections Inspector,是看不到任何时间(Event)的。这里将这个View的Class从下拉框中设为UIControl。
第二步:通过“Ctrl+drag”操作,创建UITextField的IBOutlet,命名为textFiled;
接着,声明UIControl的IBAction。选中Document Outline中的Control,通过“Ctrl+drag”操作,在对应的ViewController.h文件中,创建IBAction。
Connection选择:Action、Name:touchUpInsideAction、Type:id、Event:Touch Up Inside。
第三步:实现UIControl的Touch Up Inside事件。在ViewController.m文件中,添加以下代码:
-(IBAction)touchUpInsideAction:(id)sender
{
[self.textField resignFirstResponder];
}