March 31st, 2011Goto commentsLeave a comment
转自:http://cc.cocimg.com/bbs/read.php?tid-46356.html
在View的UITextField中经常需要输入完文字后隐藏软键盘,要实现着一点要让View的Controller实现UITextFieldDelegate代理,然后编写相应的代码。
复制代码
#import <UIKit/UIKit.h>
@interface TestVeiwController : UIViewController<UITextFieldDelegate>
{
IBOutlet UITextField *txt;
}
@property (nonatomic,retain) UITextField *txt;
@end
|
然后记得要指定文本框的代理
复制代码
- (void)viewDidLoad
{
[super viewDidLoad];
txt.delegate = self;
}
|
点击Enter的时候隐藏软键盘:
复制代码
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
|
点击取消(Cancel)或那个小差号的时候隐藏。注意这里如return YES则无法隐藏,我采用了点变通的方法。
复制代码
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
[textField resignFirstResponder];
textField.text = @”";
return NO;
}
|
点击View的其他区域隐藏软键盘。
复制代码
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[txt resignFirstResponder];
}
|
这里直接用了我自定义的变量。
设置代理的步骤比较重要,别忘记了,要不没反应。