当光标在同一条线上时,避免textview增长,顶部键盘上的textview,ios

时间:2014-01-21 20:40:07

标签: ios objective-c uitextview uiviewanimation

我在顶部键盘上添加textView进行快速回复。我正在执行以下操作来重新计算内部包含textView的容器的高度。 这是我的代码:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text 
{
    NSLog(@"inputView is %@",NSStringFromCGRect(self.inputView.frame));
    CGSize constraint = CGSizeMake(self.inputView.frame.size.width, self.inputView.frame.size.height);

    NSDictionary *stringAttributes = @{ NSFontAttributeName: [UIFont systemFontOfSize:self.inputView.font.pointSize] };

    CGSize textSize = [self.inputView.text boundingRectWithSize:constraint
                                                    options:NSStringDrawingUsesFontLeading
                                                 attributes:stringAttributes
                                                    context:nil].size;
    [UIView animateWithDuration:.2
                 animations:^{
                     CGRect r = self.frame;
                     r.origin.y -= ceil(textSize.height);       // use ceil function to avoid we have a gap between textview and kboard during transition
                     r.size.height += ceil(textSize.height);
                     self.frame = r;
                 }
                 completion:^(BOOL finished) {
                     NSLog(@"frame is %@",NSStringFromCGRect(self.frame));
                 }
     ];

    return YES;
}

然而,问题在于textView保持增长如下 enter image description here

有什么方法可以避免这种情况吗?当 text 进入第二行或点击返回时,我只希望textView增长。

1 个答案:

答案 0 :(得分:0)

请尝试以下代码:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    [UIView animateWithDuration:.2
                     animations:^{
                         CGRect frame = self.myTextView.frame;
                         if (self.myTextView.contentSize.height > frame.size.height) {
                             CGFloat offset = self.myTextView.contentSize.height - frame.size.height;
                             frame.size.height = self.myTextView.contentSize.height;
                             frame.origin.y -= ceil(offset);
                         }
                         self.myTextView.frame = frame;
                     }
                     completion:^(BOOL finished) {
                         /* completion code here */
                     }
     ];
    return YES;
}

您应该始终检查contentSize是否大于frame Height。 这就是你textView不断增长的原因 希望这能解决你的问题!