动态设置uitextview的高度,如消息应用程序

时间:2015-06-04 10:14:03

标签: ios height uitextview

我遇到设置UITextView高度消息应用的问题。它是通过在换行时增加它的高度来实现的。

我的问题是,当用户编辑文本内容时,它不会降低容器的高度,其中textview是孩子。

我正在使用自动布局和此代码

- (void)textViewDidChange:(UITextView *)textView {

    UITextPosition* pos = self.posttextView.endOfDocument;//explore others like beginningOfDocument if you want to customize the behaviour
    CGRect currentRect = [self.posttextView caretRectForPosition:pos];

    if (currentRect.origin.y > previousRect.origin.y){    
        if (self.containerHeightt.constant == 99) {        
            return;
        }

        self.containerHeightt.constant += 10;

        NSLog(@"the container height is %f",self.containerHeightt.constant);   
    }

    previousRect = currentRect;
}

请告诉我如何检测一行从textview删除,然后减少容器的高度。

1 个答案:

答案 0 :(得分:1)

请在下面 -

确保您的UITextView滚动已停用。

使用默认高度添加虚拟UITextView高度约束,并将其与

连接
IBOutlet (NSLayoutConstraint - textViewHeightConstraint). 

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textViewHeightConstraint;


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView{

    CGFloat myMaxSize = 480.0f; 

    CGRect frameRect = textView.frame;
    CGRect rect = [textView.text 
boundingRectWithSize:CGSizeMake(frameRect.size.width, CGFLOAT_MAX)
             options:NSStringDrawingUsesLineFragmentOrigin 
          attributes:@{NSFontAttributeName: textView.font} 
             context:nil];

    CGSize size = rect.size;
    if (size.height > myMaxSize) {
        size.height = myMaxSize;
        [textView setScrollEnabled:YES];
    }

    frameRect.size = size;

    self.textViewHeightConstraint.constant = size.height;  

}