iOS自定义视图 - 使用CGRect.zero进行初始化 - 约束警告

3

我有一个自定义视图,其中有两个标签垂直排布。该视图的初始化方法如下:

self.locationView = LocationView(frame: CGRect.zero)

为了将子视图定位在主视图中,我使用以下约束:

        self.gMapsView.addConstraints(
        NSLayoutConstraint.constraints(
            withVisualFormat: "H:|-[locationView]-|",
            options: NSLayoutFormatOptions(rawValue: UInt(0)),
            metrics: nil,
            views: views
        )
    )

    self.gMapsView.addConstraints(
        NSLayoutConstraint.constraints(
            withVisualFormat: "V:[locationView]-(paddingBottom)-|",
            options: NSLayoutFormatOptions(rawValue: UInt(0)),
            metrics: [
                "paddingBottom": LOCATION_VIEW_CONFIG.paddingBottom
            ],
            views: views
        )
    )

为在位置视图中定位标签,我使用以下约束:

        self.addConstraints(
        NSLayoutConstraint.constraints(
            withVisualFormat: "H:|[streetLabel]|",
            options: NSLayoutFormatOptions(rawValue: UInt(0)),
            metrics: nil,
            views: views
        )
    )

    self.addConstraints(
        NSLayoutConstraint.constraints(
            withVisualFormat: "H:|[cityLabel]|",
            options: NSLayoutFormatOptions(rawValue: UInt(0)),
            metrics: nil,
            views: views
        )
    )

    self.addConstraints(
        NSLayoutConstraint.constraints(
            withVisualFormat: "V:|-[streetLabel]-[cityLabel]-|",
            options: NSLayoutFormatOptions(rawValue: UInt(0)),
            metrics: nil,
            views: views
        )
    )

不幸的是,我收到了约束警告:

(
"<NSAutoresizingMaskLayoutConstraint:0x608000280820 h=--& v=--& Test.LocationView:0x7fdc40f0c780.height == 0   (active)>",
"<NSLayoutConstraint:0x608000280190 UILabel:0x7fdc40f0cb40.top == Test.LocationView:0x7fdc40f0c780.topMargin   (active)>",
"<NSLayoutConstraint:0x608000280320 V:[UILabel:0x7fdc40f0cb40]-(NSSpace(8))-[UILabel:0x7fdc40d155e0]   (active)>",
"<NSLayoutConstraint:0x6080002802d0 Test.LocationView:0x7fdc40f0c780.bottomMargin == UILabel:0x7fdc40d155e0.bottom   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x608000280320 V:[UILabel:0x7fdc40f0cb40]-(NSSpace(8))-[UILabel:0x7fdc40d155e0]   (active)>

如何修复它们?非常感谢 :)
1个回答

1

您需要关闭自动调整掩码,这是第一个约束条件(NSAutoresizingMaskLayoutConstraint)与您稍后创建的约束条件发生冲突。您可以看到它将高度设置为0。添加:

self.locationView.translatesAutoresizingMaskIntoConstraints = NO;

您的布局可能还存在其他问题,但这应该解决冲突。


1
非常感谢!我已经有那段代码了,但是我是在将视图添加到父视图之后才调用它的。 - user3532505

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接