ios - 像消息app一样动态设置uitextview的高度

标签 ios height uitextview

我在设置 UITextView 的高度时遇到问题,例如消息应用程序。这是通过在换行符出现时增加它的高度来实现的。

我的问题是,当用户编辑文本内容时,它并没有降低 Container 的高度,其中 textview 是一个 child 。

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

- (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 中删除一行,然后降低容器的高度。

最佳答案

请走下面的​​路-

确保您的 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;  

}

关于ios - 像消息app一样动态设置uitextview的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30641079/

相关文章:

ios - 如何使用 Swift 更改按钮的高度?

ios - 计算 UITextView 中的文本是否小于 4 MaximumNumberOfLines 限制?

iOS - NSNotificationCenter 多个UIKeyboard通知

ios - 在空的 UITextView 中启用返回键

ios - TableViewCell 上的 UIImageView 缺少对单击单元格的约束

html - 具有相对高度的元素在滚动时改变高度/跳跃(移动)

ios - 如何在文本字段中对齐此类占位符位置?

html - 如何使同级div动态填充父级?

ios - swift - UITableView 部分插入

ios - iOS 中的 View 管理