我搜索了,我甚至想出了可能的解決方案。可悲的是他們沒有一句話..我試圖通過增加它的leadingAnchor-Constraint動畫視圖的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])
}
它看起來像你正確地修改了約束,但是那裏存在與它衝突的第二個約束。在調用'updateUnderlinePosition'之前,你應該檢查爲這個視圖定義了什麼約束,我懷疑你會看到多個主要約束。就如何結束兩個主要限制而言,如果沒有看到它們是如何創建/激活的,這很難說。也許你在創建'horizontalConstraint'並激活它之前已經有了主要的約束。 – Rob
添加了創建約束的方法。 horizontalConstraint是一個全局變量,可以稍後訪問它。 – Josh