您的位置:首页 > 其它

键盘处理

2016-05-11 20:45 316 查看

键盘处理

退出键盘

[self.messageField resignFirstResponder]
[self.messageField endEditing:YES]
[self.view endEditing:YES]; // 推荐


叫出键盘

[self.messageField becomeFirstResponder]


更换键盘

UIView *keyboard = [[UIView alloc] init];
keyboard.frame = CGRectMake(0, 0, 0, 100); // 不用设置x,y,width
keyboard.backgroundColor = [UIColor redColor];
self.emailField.inputView = keyboard;


设置键盘顶部的工具条;

// 加载工具条控件
UIToolbar *toolbar = [[[NSBundle mainBundle] loadNibNamed:@"AHKeyboardTool" owner:nil options:nil] firstObject];

// 设置工具条
self.nameField.inputAccessoryView = toolbar;


监听键盘通知

- (void)viewDidLoad {
[super viewDidLoad];

// 设置文本框左边的内容
UIView *leftView = [[UIView alloc] init];
leftView.frame = CGRectMake(0, 0, 10, 0);
self.messageField.leftView = leftView;
self.messageField.leftViewMode = UITextFieldViewModeAlways;

// 监听键盘通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 键盘处理
- (void)keyboardWillChangeFrame:(NSNotification *)note {
// 取出键盘最终的frame
CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 取出键盘弹出需要花费的时间
double duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

// 修改transform
[UIView animateWithDuration:duration animations:^{
CGFloat ty = [UIScreen mainScreen].bounds.size.height - rect.origin.y;
self.view.transform = CGAffineTransformMakeTranslation(0, - ty);
}];
}


UITextFieldDelegate

#pragma mark - <UITextFieldDelegate>
/**
* 键盘弹出就会调用这个方法
*/
- (void)textFieldDidBeginEditing:(UITextField *)textField{
}
/**
* 当点击键盘右下角的return key时,就会调用这个方法
*/
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: