在View的UITextField中经常需要输入完文字后隐藏软键盘,要实现着一点要让View的Controller实现UITextFieldDelegate代理,然后编写相应的代码。
方法一:点击视图空白处隐藏
#import
#import "SecondViewController.h"
@interface ViewController : UIViewController//需要同一协议才去执行协议
@property(retain,nonatomic)UITextField *filed1,*filed2;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//添加文本框
self.fd1=[[UITextField alloc]initWithFrame:CGRectMake(80, 100, 150, 50)];
self.fd1.borderStyle=UITextBorderStyleRounded
Rect;
self.fd1.textAlignment=UITextAlignmentLeft;//默认就是左
[self.view addSubview:self.fd1];
self.fd1.delegate=self;
self.fd2=[[UITextField alloc]initWithFrame:CGRectMake(80, 180, 150, 50)];
self.fd2.borderStyle=UITextBorderStyleRounded
Rect;
[self.view addSubview:self.fd2];
self.fd2.delegate=self;
}
点击视图其他区域键盘隐藏
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.fd1 resignFirstResponder];
[self.fd2 resignFirstResponder];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterf
aceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPo
rtraitUpsideDown);
}
@end
方法二:敲回车隐藏
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return Yes;
}
把上面的程序代码红色部分,换成上面的代码就可以了