如何在UITextView中限制宽度和高度?

时间:2016-08-12 05:17:31

标签: ios objective-c autolayout uitextview

我想创建一个具有最大宽度和最小高度的UITextView。就像我们的iPhone中的“消息”应用程序中的聊天气泡一样。 我尝试使用 sizeThatFits 。但它没有给我一个很棒的尺寸。

NSString *string = @"hello everyone";
_textView = [[UITextView alloc] init];
_textView.font = [UIFont systemFontOfSize:16];
_textView.text = string;
[self.view addSubview:_textView];

CGSize size = [string sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
CGFloat finalWidth = MIN(250, size.width);
CGSize constraintSize = CGSizeMake(finalWidth, MAXFLOAT);
CGSize finalSize = [_textView sizeThatFits:constraintSize];
_textView.frame = CGRectMake(0, 0, finalSize.width, finalSize.height);

我知道我的代码有问题。所以我想知道在UITextView中正确限制宽度和高度的好方法。     谢谢

有些朋友告诉我使用Autolayout。然后我尝试这样做。这是我的代码

   [_textView mas_makeConstraints:^(MASConstraintMaker *maker){
    maker.right.equalTo(self.mas_left);
    maker.top.equalTo(self.mas_top);
    maker.width.lessThanOrEqualTo(@(250));
    maker.height.greaterThanOrEqualTo(@(40));
}];

但除非我使用 [_ textView sizeToFit] ,否则它不起作用 我的约束有什么问题吗?我希望textView根据其内容调整自己!

1 个答案:

答案 0 :(得分:-1)

  let minTextViewHeight = CGFloat(33)
  let maxTextViewHeight = CGFloat(70)
  @IBOutlet var textViewHeightConst: NSLayoutConstraint!
     func textViewDidChange(textView: UITextView) {
            //TEXTVIEW HEIGHT INCREASE WHILE TYPING
            var height = ceil(txtViewChat.contentSize.height) // ceil to avoid decimal

            if (height < minTextViewHeight) {  
                height = minTextViewHeight
            }
            if (height > maxTextViewHeight) { 
                height = maxTextViewHeight
            }
            if height != textViewHeightConst.constant { 
                textViewHeightConst.constant = height
              }
        }