使用Autolayout键盘出现时无法更改UITableView高度约束

时间:2015-02-05 13:43:51

标签: ios objective-c uitableview autolayout constraints

所以,就像Messages应用程序一样,我有一个UITableView占据了大部分屏幕。在UITableView下面,我有一个包含UITextView和UIButton的UIView。当用户单击UITextView时,会出现键盘。我已成功将UIView移动到键盘的顶部(这是我的bottomConstraint插座所做的),但我也在努力移动UITableView。

现在我在UITableView上有一个设置为528的高度约束。我已将该约束连接到Outlet,这是我的keyboardWillShow方法。

- (void)keyboardWillShow:(NSNotification *)sender {

    NSDictionary *info = [sender userInfo];
    NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect frame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect newFrame = [self.view convertRect:frame fromView:[[UIApplication sharedApplication] delegate].window];
    self.bottomConstraint.constant = newFrame.origin.y - CGRectGetHeight(self.view.frame);

    CGFloat height = CGRectGetHeight(self.view.frame) - self.composeTextView.frame.size.height - newFrame.origin.y;
    self.tableViewHeightConstraint.constant = height;

    [UIView animateWithDuration:animationDuration animations:^{
        [self.view layoutIfNeeded];
    }];}

以下是我的约束/故事板的屏幕截图。

Storyboard

^^查看控制器

UITableView Constraints

^^ UITableView约束

UIView Constraints

^^ UIView约束(包含按钮+ textview的视图)

这是我的错误:

无法同时满足约束条件。     可能至少以下列表中的一个约束是您不想要的约束。试试这个:(1)看看每个约束,并试着找出你不期望的东西; (2)找到添加了不需要的约束或约束的代码并修复它。 (注意:如果您正在查看您不了解的NSAutoresizingMaskLayoutConstraints,请参阅UIView属性的文档translatesAutoresizingMaskIntoConstraints) (

"<NSLayoutConstraint:0x174280320 V:[UITableView:0x135031c00(528)]>",

"<NSLayoutConstraint:0x17409ff40 V:[UIView:0x174184ac0(40)]>",

"<NSLayoutConstraint:0x1742807d0 V:|-(0)-[UITableView:0x135031c00]   (Names: '|':UIView:0x174184b90 )>",

"<NSLayoutConstraint:0x1742808c0 V:[UITableView:0x135031c00]-(0)-[UIView:0x174184ac0]>",

"<_UILayoutSupportConstraint:0x1740b9d40 V:[_UILayoutGuide:0x1741b3b00(0)]>",

"<_UILayoutSupportConstraint:0x1740b9ce0 _UILayoutGuide:0x1741b3b00.bottom == UIView:0x174184b90.bottom>",

"<NSLayoutConstraint:0x174280690 UIView:0x174184ac0.bottom == _UILayoutGuide:0x1741b3b00.top - 224>",

"<NSLayoutConstraint:0x174280dc0 'UIView-Encapsulated-Layout-Height' V:[UIView:0x174184b90(568)]>"

将尝试通过违反约束来恢复

NSLayoutConstraint:0x174280320 V:[UITableView:0x135031c00(528)]

1 个答案:

答案 0 :(得分:2)

这样的事情应该有用,因为你只需要设置不需要计算新帧的高度:

- (void)keyboardWillShow:(NSNotification *)sender {

NSDictionary *info = [sender userInfo];
NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect keyboardFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];


CGFloat height = self.tableViewHeightConstraint.constant-keyboardFrame.size.height-self.composeTextView.frame.size.height;
self.tableViewHeightConstraint.constant = height;

[UIView animateWithDuration:animationDuration animations:^{
    [self.view layoutIfNeeded];
}];}

如果你只是将tableView的底部约束设置为composeTextView的顶部而不是使用固定高度,似乎会更容易。这将一直有效。

相关问题