【问题标题】:Setting translatesAutoresizingMaskIntoConstraints to all subviews设置 translatesAutoresizingMaskIntoConstraints 到所有子视图
【发布时间】:2023-03-13 22:34:01
【问题描述】:

有人知道将所有子视图的 translatesAutoresizingMaskIntoConstraints 设置为 false 的含义吗?

考虑以下几点:

extension UIView {
    public func setAutoresizingMaskIntoConstraintsForAllSubviews() {
        for v in self.subviews {
            v.translatesAutoresizingMaskIntoConstraints = false
        }
    }
}
...
let cell = UITableViewCell()
cell.setAutoresizingMaskIntoConstraintsForAllSubviews() //or
cell.contentView.setAutoresizingMaskIntoConstraintsForAllSubviews()

根据我的测试,一切正常。我没有看到与任何 UIKit 组件的任何约束冲突。

根据 Apple 的文档:

默认情况下,该属性设置为 true 用于您的任何视图 以编程方式创建。如果在 Interface Builder 中添加视图, 系统自动将此属性设置为false。

https://developer.apple.com/reference/uikit/uiview/1622572-translatesautoresizingmaskintoco

【问题讨论】:

    标签: ios swift uitableview uikit constraints


    【解决方案1】:

    虽然这可能没有任何固有错误......

    首先,这不会影响子视图的子视图,除非你让它递归。

    其次,如果您使其递归,您最终将设置诸如滚动视图滚动指示器、按钮背景图像视图等的属性。

    第三,既然您这样做是因为您正在以编程方式创建视图,那么您为什么不在该代码中明确设置值?

    而且,一般来说,只是盲目地将“包罗万象”的代码扔到某处,因为你不确定发生了什么是一个非常糟糕的主意。

    【讨论】:

    • 这个讨论出现在我们的一次谈话中,当时我们试图从我们的观点中清理样板代码。我们确实讨论了您所说的所有内容,除了出于您描述的相同原因我没有考虑递归选项。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 2013-06-11
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    相关资源
    最近更新 更多