您的位置:首页 > 移动开发 > IOS开发

iOS键盘使用

2015-12-28 14:15 453 查看
一、键盘外观设置

UITextField
UITextView都遵守 UITextInputTraits协议(定义键盘属性),所以可以设置这些对象的属性来设置键盘的外观。


二、键盘通知


UIKeyboardWillShowNotification

UIKeyboardDidShowNotification

UIKeyboardWillHideNotification

UIKeyboardDidHideNotification

通知的userInfo的dic属性中
UIKeyboardFrameBeginUserInfoKey
UIKeyboardFrameEndUserInfoKey可以获取到键盘的frame信息。最好使用dic中的frame信息来进行页面适配,因为键盘高度可以变化的。(注意:只使用size不要使用origin,它总是(0,0))


三、调用和关闭


1、使用:[myTextField

becomeFirstResponder
];

2、关闭:[myTextField

resignFirstResponder];

系统会自动调用键盘,所以一般只需要负责关闭键盘就可以了。

四、键盘遮挡

当键盘遮挡住正在输入的内容,需要进行页面适配,是输入区在键盘上方。比如说在
UITableView或者UIScrollView中有一个输入框,当键盘弹起,你需要做的就是重新设置滚动视图的内容区域,然后滚动所需的文本对象的位置。因此,在UIKeyboardDidShowNotification响应方法中处理以下步骤


得到的键盘的尺寸。

通过调整键盘高度的滚动视图的底部内容插图。

滚动目标文本字段进入可视区域

处理逻辑有2种思路:
1、通过设置内容区域
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];

}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;

// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
[self.scrollView scrollRectToVisible:activeField.frame animated:YES];
}
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
2、设置偏移量
- (void)keyboardWasShown:(NSNotification*)aNotification {
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGRect bkgndRect = activeField.superview.frame;
bkgndRect.size.height += kbSize.height;
[activeField.superview setFrame:bkgndRect];
[scrollView setContentOffset:CGPointMake(0.0, activeField.frame.origin.y-kbSize.height) animated:YES];
}


如果该页面有多个输入点,可以通过以下方式获取当前响应的对象
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
activeField = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
activeField = nil;
}


阅读原文
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: