Change height of inputAccessoryView issue

Yijun picture Yijun · Dec 11, 2014 · Viewed 10.7k times · Source

When I change the height of inputAccessoryView in iOS 8, the inputAccessoryView not go to the right origin, but covers the keyboard.

enter image description here

Here are some code snippets:

in table view controller

- (UIView *)inputAccessoryView {
    if (!_commentInputView) {
        _commentInputView = [[CommentInputView alloc] initWithFrame:CGRectMake(0, 0, [self width], 41)];
        [_commentInputView setPlaceholder:NSLocalizedString(@"Comment", nil) andButtonTitle:NSLocalizedString(@"Send", nil)];
        [_commentInputView setBackgroundColor:[UIColor whiteColor]];
        _commentInputView.hidden = YES;
        _commentInputView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
    }

    return _commentInputView;
}

in CommentInputView

#when the textview change height
- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height {
    if (height > _textView_height) {
        [self setHeight:(CGRectGetHeight(self.frame) + height - _textView_height)];
        [self reloadInputViews];
    }
}

in UIView Category from ios-helpers

- (void)setHeight: (CGFloat)heigth {
    CGRect frame = self.frame;
    frame.size.height = heigth;
    self.frame = frame;
}

Answer

Yijun picture Yijun · Dec 17, 2014

Finally, i found the answer. In ios8, apple add a NSContentSizeLayoutConstraints to inputAccessoryView and set a constant with 44. You can't remove this constaint, because ios8 use it to calculate the height of inputAccessoryView. So, the only solution is to change value of this constant.

Example

in ViewDidAppear

- (void)viewDidAppear:(BOOL)animated {
    if ([self.inputAccessoryView constraints].count > 0) {
        NSLayoutConstraint *constraint = [[self.inputAccessoryView constraints] objectAtIndex:0];
        constraint.constant = CommentInputViewBeginHeight;
    }
}

change inputAccessoryView height when the textview height changed

- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height {

    NSLayoutConstraint *constraint = [[self constraints] objectAtIndex:0];
    float new_height = height + _textView_vertical_gap*2;

    [UIView animateWithDuration:0.2 animations:^{
        constraint.constant = new_height;
    } completion:^(BOOL finished) {
        [self setHeight:new_height];
        [self reloadInputViews];
    }];
}

That is.