如何以编程方式更改Anchor-Style Constraint?

时间:2016-06-15 23:37:36

标签: ios xcode swift constraints

我搜索过,我甚至提出了潜在的解决方案。可悲的是,没有一个词......我试图通过增加它的行为主导 - 约束来为视图的x位置制作动画。

我创建了这样的约束:

let margins = self.layoutMarginsGuide
    horizontalConstraint = underline.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor)

并像这样编辑约束常量:

func updateUnderlinePosition(offset:CGFloat, pageCount:Int) {

    //Underline just over width of one Screen:
    var underlineOffset = offset / CGFloat(pageCount)

    //Add left margin:
    let margins = self.layoutMarginsGuide
    underlineOffset += 15

    //reposition underlineview
    horizontalConstraint.constant += underlineOffset
    self.layoutIfNeeded()
}

为什么我会收到错误,告诉我有相互矛盾的约束?

"<NSLayoutConstraint:0x7fca2b8c72c0 UIView:0x7fca29d1c830.leading == UILayoutGuide:0x7fca2b8c4970'UIViewLayoutMarginsGuide'.leading>",
"<NSLayoutConstraint:0x7fca29c2ccd0 UIView:0x7fca29d1c830.leading == UILayoutGuide:0x7fca2b8c4970'UIViewLayoutMarginsGuide'.leading + 16.25>"

修改

约束是这样创建的:

override func layoutSubviews() {
    super.layoutSubviews()

    //underline.frame = CGRectMake(15, self.frame.height-10, 40, 2)
    underline.translatesAutoresizingMaskIntoConstraints = false
    underline.backgroundColor = UIColor.whiteColor()
    underline.layer.cornerRadius = 1.0
    self.addSubview(underline)
    print(self.backItem)
    let margins = self.layoutMarginsGuide
    horizontalConstraint = underline.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor)
    let verticalConstraint = underline.centerYAnchor.constraintEqualToAnchor(margins.bottomAnchor)
    let widthConstraint = underline.widthAnchor.constraintEqualToAnchor(nil, constant: 40)
    let heightConstraint = underline.heightAnchor.constraintEqualToAnchor(nil, constant: 2)
    NSLayoutConstraint.activateConstraints([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint])
}

2 个答案:

答案 0 :(得分:0)

检查layoutSubviews是否被调用两次

答案 1 :(得分:0)

问题是您在layoutSubviews中添加了可以多次调用的约束。您实例化underline一次,但可以多次调用layoutSubviews,引用相同的underline实例,在此过程中丢失对原始horizontalConstraint的引用。

坦率地说,添加子视图和约束并不属于layoutSubviews。您应该在实例化underline视图的地方设置约束,您可以在相应的视图init方法或awakeFromNIB中执行此操作。这取决于视图的实例化方式。