如何解决“无法同时满足约束条件”。高度约束和中心Y约束之间的冲突

时间:2019-01-04 20:02:04

标签: swift autolayout

我想在UIView中垂直居中放置UILabel。我正在使用以下约束条件:

layoutGuide = safeAreaLayoutGuide

    header.translatesAutoresizingMaskIntoConstraints = false

    titleLabel.translatesAutoresizingMaskIntoConstraints = false

    header.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
    header.rightAnchor.constraint(equalTo: layoutGuide.rightAnchor).isActive = true
    header.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
    header.heightAnchor.constraint(equalToConstant: UI.HEADER_HT).isActive = true


    titleLabel.topAnchor.constraint(equalTo: header.topAnchor, constant: SPACING.LG).isActive = true
    titleLabel.rightAnchor.constraint(equalTo: header.rightAnchor, constant: -SPACING.LG).isActive = true
    titleLabel.leftAnchor.constraint(equalTo: header.leftAnchor, constant: SPACING.LG).isActive = true
    titleLabel.heightAnchor.constraint(equalToConstant: UI.SCREEN_TITLE_HT).isActive = true
    titleLabel.centerYAnchor.constraint(equalTo: header.centerYAnchor).isActive = true

标签正确居中,但高度限制未得到遵守

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x6000003ade50 FC.StyledLabel:0x7fa077845330.height == 40.6   (active)>

1 个答案:

答案 0 :(得分:2)

如果您希望标题垂直居中,则可能不希望同时使用topAnchor和centerYAnchor约束。也许您想将该标头锚定到标签的顶部?

另外,请检出NSLayoutConstraint.activate。它将使您能够骑上所有isActive = true车。