iphone隐藏键盘代码

来源:互联网 发布:嵌入式linux如何调试 编辑:程序博客网 时间:2024/06/05 17:00

在View中使用UITextField时,经常需要输入完成后,隐藏键盘~~怎么实现呢?

要让ViewController实现UITextFieldDelegate代理,然后重写部分方法。

---------@interface ViewController---------

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextFieldDelegate>
@property(nonatomic,retain) UILabel *label;
@property(nonatomic,retain) UIButton *button;
@property(nonatomic,retain) UITextField *txtField;
-(IBAction)changeLabel:(id)sender;

@end

---------ViewController.m---------

指定文本框的代理:

- (void)viewDidLoad
{
[super viewDidLoad];
txtField.delegate = self;//一定要指定代理,往往在这里容易出现错误
}

--------点击Enter的时候隐藏键盘-------

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
    return YES;
}

--------点击view其他区域隐藏键盘--------

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[txtField resignFirstResponder];
}