gpt4 book ai didi

ios - 在添加到 subview 之前如何获取 UIView 的宽度和高度?

转载 作者:行者123 更新时间:2023-11-28 06:10:28 25 4
gpt4 key购买 nike

我正在构建一个 UIPageViewController,它具有基于 View 数组中 View 高度的可变数量的页面。

我有一个名为 BlockView 的类,如下所示:

final class BlockView: UIView {

init(viewModel: BlockViewModel) {
super.init(frame: .zero)

let primaryLabel = UILabel()
primaryLabel.text = viewModel.labelText
addSubview(primaryLabel)

constrain(primaryLabel) {
$0.top == $0.superview!.top + 8
$0.bottom == $0.superview!.bottom - 8
$0.left == $0.superview!.left + 8
$0.right == $0.superview!.right - 8
}
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

我想做的是遍历我的 BlockView 数组并运行 print(blockView.frame) 并查看不为零的帧。

现在我知道我在 BlockView.init 中将我的 frame 设置为 .zero。那是因为我希望 View 根据其标签调整自身大小。

是否需要运行某个函数才能实现此目的?

谢谢

最佳答案

尝试 sizeThatFits(_:)在不将其放入 super View 的情况下进行计算。该方法的唯一参数是 CGSize,它表示应该显示的边界。例如,如果您知道 superview 的宽度(例如 340 点)并且您想知道它需要多少高度:

let expectedSize = view.sizeThatFits(CGSize(width: 340, height: .greatestFiniteMagnitude))

但是,您的 BlockView 似乎还没有设置适当的约束。您使用 super.init(frame: .zero) 对其进行初始化 - 因此它的大小为 0,0。

并且您的约束不会改变这一点,例如:

constrain(primaryLabel) {
$0.centerY == $0.superview!.centerY
$0.left == $0.superview!.left + 8
}

这看起来像您将标签的 Y 轴中心设置为 block View 的中心,并将标签的左 anchor 设置为 View 的左 anchor 。如果 blockView 已经有了大小,那么标签就会正确定位。但是现在 block View 的大小完全不受标签大小的影响。我想您可能希望将标签限制在 blockView 的左侧、右侧、顶部和底部 anchor ,这样当您尝试计算 blockView 的大小时,自动布局必须首先计算标签的大小,并基于此计算 blockView 本身的大小。

一个可能的解决方案(我正在使用基于 anchor 的自动布局语法),您可以尝试将其放入 BlockView 的初始化程序中:

primaryLabel.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true
primaryLabel.topAchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true
primaryLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true
primaryLabel.bottomAnchor.constraint(equalTo: secondaryLabel.topAnchor, constant: -8).isActive = true
secondaryLabel.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true
secondaryLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true
secondaryLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -8).isActive = true

关于ios - 在添加到 subview 之前如何获取 UIView 的宽度和高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46866808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com