我有一个 UIScrollView,里面有多个 View ,其中一个是 UITextView。我正在尝试设置 ScrollView 的高度以匹配内容。问题是 UITextView 的高度根据它包含的文本而变化。此内容是在 View Controller 的覆盖 viewDidLoad() 方法中设置的,但由于某种原因,即使内容的值已更改,我获得的 View 高度值也不会反射(reflect)任何更改。我编写了一个函数,通过更改它的高度约束常量来更改内容 subview 的高度,我在 viewDidAppear() 方法中调用它。相关代码如下:
func setPageSize() {
var pageHeight : CGFloat {
var height : CGFloat = 1000 // The height of all content besides the UITextView
let descriptionTextViewHeight = self.descriptionTextView.frame.height
height += descriptionTextViewHeight
return height // Always returns 60, which is the height of view when using the placeholder text from interface builder (doesn't update when text updated).
}
self.pageViewHeightConstraint.constant = pageHeight
}
override func viewDidLoad() {
super.viewDidLoad()
self.descriptionTextView.text = self.description
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
self.setPageSize()
}
我应该在其他地方调用 setPageSize() 方法吗? UITextView 中是否有一种方法可以在输入新文本时返回更新后的值?我也尝试使用内容 View 中最后一个 View 的位置作为设置高度的引用,但我遇到了同样的问题 - 它返回的值就好像 UITextView 的高度始终为 60,但事实并非如此。
最佳答案
使用
let descriptionTextViewHeight = self.descriptionTextView.frame.height
返回textView的可见高度, 要获取 textView 内可滚动内容的高度,您可以使用
let descriptionTextViewHeight = self.descriptionTextView.contentSize.height
关于ios - Swift UIScrollView 高度取决于 UITextView 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49541512/