I have a UIView that contains a UIScrollView, and that UIScrollView contains another UIView, which contains labels etc. Sometimes, certain labels contain 3 lines of text, sometimes they contain 15,... depending on the received data. The view also changes when certain buttons get clicked. When I scroll through my screen, it doesn't go al the way to the bottom. I notice that the height of the labels in label.frame.height is way smaller than the actual height of the label. How can I get the actual size of the labels at runtime? Anyone that can help?
I've tried overriding function viewDidLayoutSubviews:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
contentview.layoutSubviews()
var contentHeigt: CGFloat = 0
for subview in contentview.subviews{
contentHeigt += subview.frame.height
}
scrollView.contentSize = CGSize(width: scrollView.frame.width, height: contentHeigt)
}
but that's where the height doesn't seem to match the actual height.
I've tried this:
func getLableHeightRuntime(label:UILabel) -> CGFloat {
let stringValue = label.text!
let width:CGFloat = 0
let height:CGFloat = 0
let font = UIFont(name: UIFont.systemFont(ofSize: 17).fontName, size: 17)
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = stringValue.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
return ceil(boundingBox.height)
}
seems to give back the right size, but when I add that to the contentHeight in viewDidLayoutSubviews, like this:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
contentview.layoutSubviews()
var contentHeigt: CGFloat = 0
for subview in contentview.subviews{
contentHeigt += subview.frame.size.height
}
contentHeigt += getLableHeightRuntime(label: lblLocations)
contentHeigt += getLableHeightRuntime(label: lblTeachers)
scrollView.contentSize = CGSize(width: scrollView.frame.width, height: contentHeigt)
}
I can't click certain buttons, and it scrolls way too far.