UITextView动态更改大小

时间:2016-09-03 18:04:29

标签: ios swift uitextview nslayoutconstraint uitextviewdelegate

我使用以下代码动态调整包含containerView

UITextView的高度
    func textViewDidChange(textView: UITextView) {
    let amountOfLinesToBeShown:CGFloat = 6
    let maxHeight:CGFloat = textView.font!.lineHeight * amountOfLinesToBeShown

    if ((textView.contentSize.height / textView.font!.lineHeight) < 6) {
        topConstraint?.constant = -textView.sizeThatFits(CGSizeMake(textView.frame.size.width, maxHeight)).height - keyboardFrameSize!.height

        containerView.layoutIfNeeded()
        containerView.updateConstraints()
    }
}

问题是,当我打字时,它看起来像这样: enter image description here

并且期望的效果是:

enter image description here

4 个答案:

答案 0 :(得分:1)

以下代码可能是您遇到此问题的解决方案。

   func textViewDidChange(textView: UITextView) {
        var newFrame = textView.frame
        var minHeight = 40 // ENTER THE MIN HEIGHT OR THE INITIAL HEIGHT OF THE TEXTVIEW
        var maxHeight = 100 // ENTER THE MAX HEIGHT YOU WANT
        newFrame.size  = textView.sizeThatFits(CGSizeMake(newFrame.size.width, maxHeight)) 

    if newFrame.size.height > minHeight && newFrame.size.height < maxHeight {
        // Change the origin.y value which is 10 to your desired margin for top.
        textView.frame = CGRectMake(0, 10, textView.frame.size.width, newFrame.size.height)
    }
}

答案 1 :(得分:0)

创建一个函数并将其添加到viewDidLoad方法中,尝试使用:

self.addSubview(containerView)
containerView.addSubview(textView)

containerView.bottomAnchor.constraintEqualToAnchor(self.bottomAnchor).active=true
containerView.leftAnchor.constraintEqualToAnchor(self.leftAnchor).active=true

textView.topAnchor.constraintEqualToAnchor(containerView.topAnchor, constant: 3).active=true
textView.leftAnchor.constraintEqualToAnchor(containerView.leftAnchor, constant: 3).active=true
textView.widthAnchor.constraintEqualToAnchor(containerView.widthAnchor).active=true
textView.heightAnchor.constraintEqualToAnchor(containerView.heightAnchor).active=true

答案 2 :(得分:0)

使用 textview textContainerInset方法来实现您想要的内容

//insets are top, left, bottom, top..
tv.textContainerInset = UIEdgeInsetsMake(0,0,0,0);

设置此方法后,当textview行开始时,增加textview的高度以查找textview next line start,

使用方法: - TextViewDidChange

答案 3 :(得分:0)

这篇文章的最佳答案解决了这个问题。 How do I size a UITextView to its content?

下面的代码不是我的,它来自上面链接的答案(只是为了其他方便而发布):

let fixedWidth = textView.frame.size.width
textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height:CGFloat.max))
var newFrame = textView.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
textView.frame = newFrame;