TextView没有正确调整大小

时间:2018-01-16 21:06:16

标签: ios swift uitableview uitextview

我有一个带有textview的tableview单元格:

class DetailsCell: UITableViewCell, UITextViewDelegate {


    let detailsTextView: UITextView = {
        let tv = UITextView()
        tv.font = UIFont(name: "AvenirNext-Medium", size: 24)
        tv.isScrollEnabled = false
        tv.textColor = .white
        tv.backgroundColor = .clear
        tv.translatesAutoresizingMaskIntoConstraints = false
        return tv
    }()


    func textViewDidChange(_ textView: UITextView) {
        let addTodoViewController = AddTodoViewController()
        addTodoViewController.begindEndUpdate()
    }



    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: .default, reuseIdentifier: "DetailsCell")

        addSubview(detailsTextView)
        detailsTextView.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true
        detailsTextView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
        detailsTextView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true
        detailsTextView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true


        backgroundColor = .black

        textLabel?.isHidden = true

        detailsTextView.delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

当我加载应用程序并且textview已经有一个以编程方式分配的文本时,单元格正确地获得了正确的高度并且textview被正确调整大小,但是当我尝试更改textview的文本时,单元格和textview不要调整大小。有人能帮我吗?

 override func viewWillAppear(_ animated: Bool) {
    toDoTextField.becomeFirstResponder()
    addTodoTableView.estimatedRowHeight = 60
    addTodoTableView.rowHeight = UITableViewAutomaticDimension
}

Textview with not initial text Image

Textview with initial text Image

1 个答案:

答案 0 :(得分:0)

UITextView在内容更改时不会自行调整大小。您必须编写一些代码来调整textView的大小,然后相应地调整单元格的高度。可能这可以帮助你resizing textview to its content

或者您可以使用某个第三方库而不是默认UITextView,例如GrowingTextView