当键盘弹出自动布局时调整UITextView的大小

时间:2013-01-03 14:10:53

标签: ios objective-c xcode layout

我想在键盘出现时调整UITextView的大小,但我似乎无法做到这一点。我在其中创建了一个带有UITextView的视图。在代码中,我想手动调整此文本视图的高度。我这样做:

_textView.translatesAutoresizingMaskIntoConstraints  = NO;

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:_textView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:216.0f];
[_textView addConstraint:constraint];

在Interface Builder中,我说文本视图和超级视图之间的边距可以大于或等于0.

当我运行应用程序时,它会给出错误,即不能同时满足约束:

"<NSLayoutConstraint:0x886e550 V:[UITextView:0x7b0fa00(216)]>",
"<NSLayoutConstraint:0x886f7c0 UITextView:0x7b0fa00.bottom == UIView:0x886e3c0.bottom>",
"<NSLayoutConstraint:0x886f700 V:|-(0)-[UITextView:0x7b0fa00]   (Names: '|':UIView:0x886e3c0 )>",
"<NSAutoresizingMaskLayoutConstraint:0x71a2d10 h=--- v=--- V:[UIWindow:0x8a792f0(480)]>",
"<NSAutoresizingMaskLayoutConstraint:0x71a1490 h=-&- v=-&- UIView:0x886e3c0.height == UIWindow:0x8a792f0.height - 20>"


Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x886e550 V:[UITextView:0x7b0fa00(216)]>

我不确定如何确保满足所有约束条件。有人能帮我一把吗?

谢谢!

2 个答案:

答案 0 :(得分:8)

使用iOS7,设置UIEdgeInsets而不是调整视图大小可能会更好,因为我们有时会处理半透明。在某些应用程序中,我们仍然希望看到文本滚动浏览工具栏,键盘或其他UI叠加层。另一个好处是,通常不需要动画内容的更改,因为这种情况发生在“幕后”。

Apple在他们的开发人员资源中提供了一个非常简单和优雅的解决方案,尽管它有点埋没且很难找到。这是一个链接:

https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html

转到清单5-1以获取完整的代码段。

答案 1 :(得分:-1)

可能重复

How to resize UITextView on iOS when a keyboard appears?

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) 
                                             name:UIKeyboardWillShowNotification object:self.view.window]; 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) 
                                             name:UIKeyboardWillHideNotification object:self.view.window]; 

- (void)keyboardWillShow:(NSNotification *)notif
{
[thetextView setFrame:CGRectMake(20, 49, 280, 187)]; //Or where ever you want the view to go


}

- (void)keyboardWillHide:(NSNotification *)notif
{
[thetextView setFrame:CGRectMake(20, 49, 280, 324)]; //return it to its original position

}