[英]Size of UITextView after setting its height depending of its content SWIFT
I have a UITextView, with a height constraint in order to adapt the height of the frame to its content (depending of the length of the string). 我有一个UITextView,具有高度限制,以便使框架的高度适应其内容(取决于字符串的长度)。 (I use autolayout).
(我使用自动版式)。 It works fine.
工作正常。
But, I don't understand something about the size of the textview frame. 但是,我对textview框架的大小一无所知。
I explain. 我解释。
I display the frame infos after setting the text of the uitextview, and after updating the constraint. 在设置uitextview的文本以及更新约束之后,我将显示框架信息。
override func viewDidLoad() {
...
self.textview.text = post.title
...
}
override func viewDidLayoutSubviews() {
let contentSize = self.textview.sizeThatFits(self.textview.bounds.size)
self.heightConstraint.constant = contentSize.height
self.textview.layoutIfNeeded()
print(self.textview.frame) // frame
print(self.textview.bounds) // bounds
}
The result: 结果:
For case A: 对于情况A:
(8.0, 0.0, 584.0, 97.0) //frame
(0.0, 0.0, 584.0, 97.0) //bounds
For case B: 对于情况B:
(8.0, 0.0, 584.0, 97.0) //frame
(0.0, 0.0, 584.0, 97.0) //bounds
I don't understand why the height of the frame is the same in both case??? 我不明白为什么两种情况下镜框的高度都一样???
This will solve the problem if you don't need the scrolling part of the UITextView
: 如果您不需要
UITextView
的滚动部分,这将解决问题:
class ViewController: UIViewController {
let textView = UITextView()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.view.addSubview(self.textView)
self.textView.backgroundColor = UIColor.redColor()
self.textView.text = "Hello world Hello world Hello world Hello world Hello world Hello world"
self.textView.translatesAutoresizingMaskIntoConstraints = false
self.textView.topAnchor.constraintEqualToAnchor(self.view.topAnchor).active = true
self.textView.leftAnchor.constraintEqualToAnchor(self.view.leftAnchor).active = true
self.textView.rightAnchor.constraintEqualToAnchor(self.view.rightAnchor).active = true
self.textView.scrollEnabled = false // magic which will help auto expanding
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.