ios 如何在Swift中使用sizeThatFits?

vd2z7a6w  于 2023-06-07  发布在  iOS
关注(0)|答案(1)|浏览(199)

我有一个文本视图和这样的视图

let lb = UITextView()
let view = UIView()
background_img_view.addSubview(about_txt)

lb没有固定的高度,它可以是30或300px,我如何使用sizeThatFits使background_img_view的高度依赖于lb的?

z2acfund

z2acfund1#

试试这个:

// Get the width you want to fit
let fixedWidth = textView.frame.size.width

// Calculate the biggest size that fits in the given CGSize
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))

// Set the textView's size to be whatever is bigger: The fitted width or the fixedWidth
textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)

// Make the "background_img_view" height match the textView's height
background_img_view.frame.size.height = textView.frame.size.height

相关问题