how to make UITextView height dynamic according to text length?

前端 未结 21 2360
隐瞒了意图╮
隐瞒了意图╮ 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 06:15

    1 Add an observer to the content length of textfield

       yourTextView.addObserver(self, forKeyPath: "contentSize", options: (NSKeyValueObservingOptions.new), context: nil);
    

    2 Implement observer

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            let tv = object as! UITextView;
            var topCorrect = (tv.bounds.size.height - tv.contentSize.height * tv.zoomScale)/2.0;
            topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
            tv.contentOffset.x = 0;
            tv.contentOffset.y = -topCorrect;
            self.yourTextView.contentSize.height = tv.contentSize.height;
            UIView.animate(withDuration: 0.2, animations: {
                self.view.layoutIfNeeded();
            });
        }
    

提交回复
热议问题