UIView固定框架

发布于 2025-01-13 04:25:24 字数 192 浏览 2 评论 0原文

我制作了一个自定义视图,我希望该视图的大小是固定的。
就像 UISwitch 一样,你甚至无法更改高度和宽度值。
或者像 UILabel。我想将视图添加到情节提要,而不添加任何高度或宽度约束,并且不存在丢失约束错误。
我已经覆盖了内在内容大小,但仍然收到缺少约束的错误。
有没有什么方法可以使视图的高度和宽度恒定,甚至无法获取值?

I made a customView and I want the size of that view to be fixed.

Like UISwitch in which you can't even change the height and width value.
Or like UILabel. I want to add the view to storyboard without adding any height or width constraint with no missing constraint error.
I already override intrinsicContentSize but I still get the missing constraint error.
Is there any way to make height and width of a view constant that don't even get values?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淑女气质 2025-01-20 04:25:24

简单的解决方案

您可以覆盖intrinsicContentSize变量并返回视图的固定大小。

因此,这样的事情应该在您的自定义视图类中起作用:

override var intrinsicContentSize: CGSize {
    return CGSize(width: <Your width>, height: <Your height>)
}

更高级

添加 intrinsicContentSize 会起作用,但是如果用户添加高度约束,它可能会使视图混乱或更改视图的高度以匹配约束。如果您知道自定义视图的高度不应更改,那么您可以手动更改视图的高度限制。

override func updateConstraints() {
    super.updateConstraints()
        
    if let constraint = self.constraints.first(where: { constraint in
        return constraint.isActive && constraint.firstAttribute == .height
    }) {
       constraint.constant = <Height of View>
    }
}

理想情况下,你最好不要添加这个,但我只是在这里添加这个,所以如果有人需要它,它是一个选项。

Simple solution

You can override the intrinsicContentSize variable and return the fixed size of your view.

So something like this should work in your custom view class:

override var intrinsicContentSize: CGSize {
    return CGSize(width: <Your width>, height: <Your height>)
}

More Advanced

Adding the intrinsicContentSize will work, but if a user adds a height constraint it can make the view confused or change the height of the view to match the constraint. If you Know the height of your custom view shouldn't change then you can manually change the height constraints from your view.

override func updateConstraints() {
    super.updateConstraints()
        
    if let constraint = self.constraints.first(where: { constraint in
        return constraint.isActive && constraint.firstAttribute == .height
    }) {
       constraint.constant = <Height of View>
    }
}

Ideally though, your best not adding this, but I'm just adding this here so it's an option if anyone needs it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文