how to make UITextView height dynamic according to text length?

前端 未结 21 2313
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 05:44

As you can see in this image

the UITextView changes it\'s height according to the text length, I want to make it adjust it\'s height according to the te

21条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 05:54

    Swift 4+

    This is extremely easy with autolayout! I'll explain the most simple use case. Let's say there is only a UITextView in your UITableViewCell.

    • Fit the textView to the contentView with constraints.
    • Disable scrolling for the textView.
    • Update the tableView in textViewDidChange.

    (You can do the last step in two ways - either pass the tableView instance to the cell or set the textView delegate to your view controller and implement the textViewDidChange delegate there and update the table view.)

    That's all!

    class TextViewCell: UITableViewCell {
    
        //MARK: UI Element(s)
        /// Reference of the parent table view so that it can be updated
        var tableView: UITableView!
    
        lazy var textView: UITextView = {
            let textView = UITextView()
            textView.isScrollEnabled = false
            // Other textView properties
            return textView
        }()
    
        //MARK: Padding Variable(s)
        let padding: CGFloat = 50
    
        //MARK: Initializer(s)
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
    
            addSubviews()
            addConstraints()
    
            textView.becomeFirstResponder()
        }
    
        //MARK: Helper Method(s)
        func addSubviews() {
            contentView.addSubview(textView)
        }
    
        func addConstraints() {
            textView.leadingAnchor  .constraint(equalTo: contentView.leadingAnchor, constant: padding).isActive = true
            textView.trailingAnchor .constraint(equalTo: contentView.trailingAnchor, constant: -padding).isActive = true
            textView.topAnchor      .constraint(equalTo: contentView.topAnchor, constant: padding).isActive = true
            textView.bottomAnchor   .constraint(equalTo: contentView.bottomAnchor, constant: -padding).isActive = true
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    }
    
    extension TextViewCell: UITextViewDelegate {
    
        func textViewDidChange(_ textView: UITextView) {
            self.tableView.beginUpdates()
            self.tableView.endUpdates()
        }
    
    }
    

    Check out my repo for the full implementation.

提交回复
热议问题