简体   繁体   中英

Swift UIScrollView height dependent upon UITextView content

I have a UIScrollView with multiple views inside of it, one of them being a UITextView. I'm trying to set the height of scroll view to match the content. The problem is that the UITextView has a height that varies according to the text it contains. This content is set in the override viewDidLoad() method in the view controller, but for some reason the value I get for the height of the view does not reflect any changes, even after the value of the content has changed. I have a function written to change the height of the content subview by changing it's height constraint constant, which I am calling in the viewDidAppear() method. Relevant code is as follows:

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()
}

Should I call the setPageSize() method somewhere else? Is there a method in UITextView that returns an updated value when new text is entered? I have also tried using the location of the last view in the content view for reference in setting the height, but I'm having the same problem - it's returning a value as if the UITextView's height is always 60, which it's not.

Using

let descriptionTextViewHeight = self.descriptionTextView.frame.height

returns visible height of the textView, To get height of the scrollable content inside the textView , you can use

let descriptionTextViewHeight = self.descriptionTextView.contentSize.height

OK. I'm not certain why this works, but if I put this line that sets the value of the text:

self.descriptionTextView.text = self.description

in viewDidLayoutSubviews() instead of viewDidLoad() it works. I'm not sure why that is, since viewDidLoad() is called before viewDidLayoutSubviews(), and both are called before viewDidAppear(); but for some reason this returns the proper value of the UITextView's height with:

self.descriptionTextView.frame.height

in the viewDidAppear() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM