1.当向一个输入框输入文字时,虚拟键盘可能会弹起覆盖掉输入框。为了解决这个问题,我们需要让输入框跟随键盘一起移动。当键盘有活动时,会发送一条对应的通知。
UIKeyboardWillShowNotification
UIKeyboardDidShowNotification
UIKeyboardWillHideNotification
UIKeyboardDidHideNotification
利用此通知,我们可以改变输入框的位置,避免输入框被键盘所覆盖掉。
通知UIKeyboardWillShowNotification包含的消息如下:
{name = UIKeyboardWillChangeFrameNotification; userInfo = {
UIKeyboardAnimationCurveUserInfoKey = 7;
UIKeyboardAnimationDurationUserInfoKey = "0.25";
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 253}}";
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 606.5}";
UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 353.5}";
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 480}, {320, 253}}";
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 227}, {320, 253}}";
}}
由此我们可以获取键盘弹出时的各种属性,然后重新设置输入框的位置
CGFloat time = [notification.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
[UIView animateWithDuration:time animations:^{
CGRect rect = [notification.userInfo[@"UIKeyboardBoundsUserInfoKey"] CGRectValue];
self.chatView.transform = CGAffineTransformMakeTranslation(0, -rect.size.height);
}];
2.当点击return按键,希望键盘消失。有以下几种解决方案
(1)当输入框为textField时,我们可以利用它的代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
监听return按键的点击,然后让输入框丢失第一响应,键盘消失
(2)当输入框为textView时,我们可以利用代理方法
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if ([text isEqualToString:@"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}
当点击return时候,丢失第一响应。
备注:我们还可以利用此代理方法,限制输入文字的字数,textfield也有类似方法
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if (range.location>=100)
{
return NO;
}
else
{
return YES;
}
}