如何在iphone中隐藏键盘?
有两个uiTextFields
,但是按了返回键之后键盘不能隐藏。
不知道该怎么办
多谢
在你的View或ViewController开始时要设置UITextFieldDelegate 协议:
@interface YourViewController : UIViewController <UITextFieldDelegate>
然后在.m文件中添加UITextFieldDelegate Protocol
方法:
- (BOOL)textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder]; return YES;}
最后,初始化.m文件中的textfield后,
yourTextField=[[UITextField alloc] initWithFrame:yourFrame];
下一行非常重要
yourTextField.delegate = self; //viewcontroller或者view关联到textField
要让ViewController实现UITextFieldDelegate代理,然后重写部分方法。
---------@interface ViewController---------
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITextFieldDelegate>
{
IBOutlet UILabel *label;
IBOutlet UIButton *button;
IBOutlet UITextField *txtField;
}
@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];
}