iOS_UITextField_回收键盘的几种方法

控件关键字: 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];

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值