设置 Text input traits ---》Return key 为DONE
去掉auto-enable Return key 选中状态。
创建一个类为:
@interface BoardReturn : NSObject <UITextFieldDelegate> {
}
@end
@implementation BoardReturn
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
@end
在你的Controller中加入此类
#import "Controller.h"
#import "BoardReturn.h"
@implementation Controller
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
//view上的UIinputfiled 对应的 IBoutlet.
myText.clearButtonMode=UITextFieldViewModeWhileEditing;
myText.delegate=[[[BoardReturn alloc] init] autorelease];
[super viewDidLoad];
}
增加UITextFieldDelegate委托
//重新定位view的坐标
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
// When the user presses return, take focus away from the text field so that the keyboard is dismissed.
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
self.view.frame = rect;
[UIView commitAnimations];
[textField resignFirstResponder];
return YES;
}
//隐藏键盘
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
CGRect frame = textField.frame;
int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);//键盘高度216
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
[UIView setAnimationDuration:animationDuration];
float width = self.view.frame.size.width;
float height = self.view.frame.size.height;
if(offset > 0)
{
CGRect rect = CGRectMake(0.0f, -offset,width,height);
self.view.frame = rect;
}
[UIView commitAnimations];
}
iOS开发中,发现UITextView没有想UITextField中textFieldShouldReturn:这样的方法,那么要实现UITextView return键隐藏键盘,可以通过判断输入的字符是不是回车符来实现。
首先,声明要实现UITextView 的delegate。
[plain]
@interface MyViewController :UIViewController <UITextViewDelegate>
然后, 设置textView的delegate.
textView.delegate =self;
通常在viewDidLoad中设置此属性,或在nib(或storyboard)中。
最后,实现代理方法。
//隐藏键盘
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
if ([text isEqualToString:@"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}