我想在键盘出现时调整文本视图的大小。我的代码如下。我打开了自动布局,因此使用来自超级视图的 textView->bottom 空间的约束,并通过 IBOutlet distanceFromBottom 引用它。
- (void)keyboardWillShow:(NSNotification *)notification
{
[UIView animateWithDuration:0.3 animations:^{
NSDictionary* d = [notification userInfo];
CGRect r = [d[UIKeyboardFrameEndUserInfoKey] CGRectValue];
r = [textView convertRect:r fromView:Nil];
if(IS_IPHONE_6||IS_IPHONE_6P)
distanceFromBottom.constant = r.origin.y+78;
else if(IS_IPHONE_5)
distanceFromBottom.constant = r.origin.y+183;
}];
}
上面的代码完美运行。我不明白的是为什么我需要为iPhone6添加+78或为iPhone5添加183。这两个值是我通过反复试验得出的。如果我不添加这些,则 textView 会延伸到键盘下方。请帮我解开这个谜团。
In viewWillAppear
方法,添加以下内容:
- (void) viewWillAppear:(BOOL)paramAnimated{
[super viewWillAppear:paramAnimated];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(handleKeyboardDidShow:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(handleKeyboardWillHide:)
name:UIKeyboardWillHideNotification object:nil];
}
然后实现通知中心的两个方法,如下:
- (void) handleKeyboardDidShow:(NSNotification *)paramNotification{
NSValue *keyboardRectAsObject =
[[paramNotification userInfo]
objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = CGRectZero;
[keyboardRectAsObject getValue:&keyboardRect];
yourTextView.contentInset =
UIEdgeInsetsMake(0.0f,
0.0f,
keyboardRect.size.height,
0.0f);
}
另一种是这样的:
- (void) handleKeyboardWillHide:(NSNotification *)paramNotification{
yourTextView.contentInset = UIEdgeInsetsZero;
}
它将适用于所有设备;)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)