如何在Swift中使用sizeThatFits?

SIA*_*AJA 3 uitextview uiview ios swift

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

let lb = UITextView()
let view = UIView()
background_img_view.addSubview(about_txt)
Run Code Online (Sandbox Code Playgroud)

lb没有固定的高度,它可以是30或300像素,我该如何sizeThatFits使background_img_view'的高度取决于lb'?

nik*_*_me 5

尝试这个:

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

// Calculate the biggest size that fixes 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
Run Code Online (Sandbox Code Playgroud)

  • 你能在每一行代码中添加一些注释来说明它的作用吗? (2认同)