如何使用自动布局动态设置textview高度

时间:2018-09-20 04:36:28

标签: ios swift autolayout textview storyboard

需要设置一个文本视图,其初始高度enter image description here像这样

用户输入文本时,必须将textview的高度增加到一定高度

enter image description here

如何使用自动布局实现此目的,这就是我的自动布局约束的样子 enter image description here

3 个答案:

答案 0 :(得分:2)

尝试一下

/// Orignal Height for Text View
var orignalHeight : CGFloat?

/// Height Constraint of Text View
@IBOutlet weak var descriptionTVHeightConstraint: NSLayoutConstraint!

/// In ViewDidLayoutSubviews Get Height
self.orignalHeight = self.descriptionTextView.frame.size.height

func textViewDidChange(_ textView: UITextView) {
        /// Get Width Which will be always same
        let fixedWidth = textView.frame.size.width

        /// Here we need to get The height as Greatest that we can have or expected
        textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))

        /// Get New Size 
        let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))

        /// New Frame
        var newFrame = textView.frame
        newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)

        /// Orignal height is height that is assigned to TextView for first time and 100 is maximum height that textview can increase 
        self.descriptionTVHeightConstraint.constant = min(100,max(Int(newFrame.size.height),Int(self.orignalHeight!))



        bookSessionStruct.sessionTopicDiscussion = textView.text!.trimmed()

    }

答案 1 :(得分:0)

UITextView的{​​{1}}设置为false,然后isScrollEnabled将自动适合其大小。

并且请记住不要为具有恒定值的高度锚点添加约束:

UITextView

希望有帮助。

答案 2 :(得分:0)

enter image description here

UITextView放入另一个容器视图(此处为红色),然后像下面提到的图像一样设置容器视图的constraints

enter image description here

UITextView中的

containerview将具有leading trailing top bottom约束与containerview对齐(红色为)。

此后,您必须获取容器视图的height约束和bottom约束的引用出口(下面提供的图像)。

enter image description here

之后,将下面显示的代码放入viewDilLoad方法中……

enter image description here

然后只需写下这两种方法来控制其余的事情。还有 Hola !你是冠军!你已经做到了。

//MARK: TextView delegate

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if(text == "\n") {
        textView.resignFirstResponder()
        return false
    }
    return true
}


func textViewDidChange(_ textView: UITextView) {


    let fixedWidth = textView.frame.size.width
    textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
    let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
    var newFrame = textView.frame
    newFrame = CGRect.init(x: newFrame.origin.x, y: newFrame.origin.y+newFrame.height-newSize.height, width: max(newSize.width, fixedWidth), height: newSize.height)

    let newHeight = newFrame.size.height as CGFloat

    Swift.print("height: %f",newHeight)

    if newHeight > 40 && newHeight <= 105
    {
        chatBoxContainerViewHeightConstraint.constant = newHeight + 16
        UIView.animate(withDuration: 0.3) {
            self.view.layoutIfNeeded()
        }
    }
    else if newHeight <= 40
    {
        chatBoxContainerViewHeightConstraint.constant = 56
        UIView.animate(withDuration: 0.3) {
            self.view.layoutIfNeeded()
        }
    }

}


@objc func keyboardWillChangeFrame(_ notification: NSNotification) {

    if let userInfo = notification.userInfo {

        let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
        let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
        let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue
        let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)

        let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
        let endFrameY = endFrame?.origin.y ?? 0
        let tabbarHeight = self.tabBarController?.tabBar.frame.size.height
        if (endFrameY >= UIScreen.main.bounds.size.height) {
            Swift.print("----< %f",endFrameY)
            self.bottomViewBottomConstraint.constant = 0
        } else  {
            Swift.print("----> %f",endFrameY)
            self.bottomViewBottomConstraint.constant = -((endFrame?.size.height)!-tabbarHeight! )
        }
        UIView.animate(withDuration: duration,
                       delay: TimeInterval(0),
                       options: animationCurve,
                       animations: { self.view.layoutIfNeeded() },
                       completion: nil)
    }
}