【问题标题】:How to use sizeThatFits in Swift?如何在 Swift 中使用 sizeThatFits?
【发布时间】:2017-08-05 00:43:31
【问题描述】:

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

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

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

【问题讨论】:

    标签: ios swift uiview uitextview


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 你能在每一行代码中添加一些 cmets 来说明它的作用吗?
    猜你喜欢
    • 2013-11-06
    • 2016-05-26
    • 1970-01-01
    • 2015-09-21
    • 2021-04-05
    • 2014-09-18
    • 2014-10-26
    • 2018-12-12
    • 2021-05-15
    相关资源
    最近更新 更多