控件关键字: resignFirstResponder, UITextFieldDelegate, textFieldShouldReturn
UI_回收键盘的方法
回收键盘的方法,很多, 思路也很多.项目中要灵活使用
先提供几种思路和方法
1. UITextField输入之后, 点选某Button回收键盘
在Button的点击设置方法中进行设置
- (void)buttonClicked:(UIButton *)button
{
// 1.找到弹出键盘的textField
UITextField *textField = (UITextField *)[self.window viewWithTag:10000];
// 2.回收键盘
[textField resignFirstResponder];
}
2. 使用UITextFieldDelegate协议代理的方法, 在TextField输入完数据,点击虚拟键盘的"回车键"回收键盘
// 1. 签订协议
@interface MainViewController : UIViewController <UITextFieldDelegate>
<pre name="code" class="objc">- (void)viewDidLoad
{
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, 280, 40)];
textField.backgroundColor = [UIColor clearColor];
[self.view addSubview:textField];
[textField release];
// 2.指定代理人
textField.delegate = self;
}
// 3.编写协议方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
// 回收键盘
[textField resignFirstResponder];
return YES;
}
3. 使用手势API, 实现键盘的回收.例如, 点击空白处, 在空白处向下轻扫的动作
在主视图中创建一个TextField对象.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
UITextField *textField1 = [[UITextField alloc] initWithFrame:CGRectMake(100, 60, 180, 40)];
textField1.backgroundColor = [UIColor clearColor];
textField1.placeholder = @"请输入用户名";
textField1.borderStyle = 3;
textField1.tag = 100;
[self.view addSubview:textField1];
[textField1 release];
// 轻扫空白处键盘回收
UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe:)];
// 轻扫方向, 向下轻扫
swipe.direction = UISwipeGestureRecognizerDirectionDown;
[self.view addGestureRecognizer:swipe];
[swipe release];
// 点击空白处键盘回收
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
[self.view addGestureRecognizer:tap];
[tap release];
}
// 方法的实现
- (void)tap:(UITapGestureRecognizer *)tap
{
// 根据Tag值,获取textField
UITextField *textField = (UITextField *)[self.view viewWithTag:100];
[textField resignFirstResponder];
}
- (void)swipe:(UISwipeGestureRecognizer *)swipe
{
// 根据Tag值,获取textField
UITextField *textField = (UITextField *)[self.view viewWithTag:100];
[textField resignFirstResponder];
}