如何在 Swift 中使用 sizeThatFits? [英] How to use sizeThatFits in Swift?

查看:53
本文介绍了如何在 Swift 中使用 sizeThatFits?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have got a text view and a view like this

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

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

lb doesn't have fixed height,it can be 30 or 300px,how can i use sizeThatFits to make background_img_view's height depend on lb's?

推荐答案

试试这个:

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

这篇关于如何在 Swift 中使用 sizeThatFits?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆