代码之家  ›  专栏  ›  技术社区  ›  Midhun Narayan

如何使用autolayout动态设置textview高度

  •  0
  • Midhun Narayan  · 技术社区  · 6 年前

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

    当用户输入文本时,文本视图的高度必须增加到一定的高度

    enter image description here

    如何使用autolayout实现这一点?这就是我的autolayout约束的外观 enter image description here

    3 回复  |  直到 6 年前
        1
  •  3
  •   Prashant Tukadiya    6 年前

    试试这个

    /// 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()
    
        }
    
        2
  •  0
  •   likeSo    6 年前

    UITextView isScrollEnabled UITextView视图 会自动调整大小。

    请记住,不要为具有常量值的高度锚点添加约束:

    textView.snp.makeConstraints{ (maker) in maker.height.greaterThanOrEqualTo(xxx) }
    

        3
  •  0
  •   Koustov Basu    6 年前

    enter image description here

    把钥匙放好 UITextView 在另一个容器视图中(此处为红色),并设置 constraints 像下面提到的图片一样。

    enter image description here

    UITextView视图 containerview leading trailing top bottom 约束与 集装箱视图

    在那之后,你必须走出口的参考 height 约束(&A); 底部

    enter image description here

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

    enter image description here

    然后写下这两种方法来控制剩下的事情。以及 赫拉 ! 你是冠军!你成功了。

    //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)
        }
    }