如何在Swift中使用sizeThatFits?

5

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

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

lb没有固定的高度,可能是30或300像素,我该如何使用sizeThatFitsbackground_img_view的高度取决于lb的高度?

1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
9

试试这个:

// 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

2
你能否给每行代码加上注释,说明其功能是什么? - traisjames

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,