我正在编写基于网格的视图,使用以下代码动态添加 NSLayoutConstraints
for (x, column) in enumerate(board) {
for (y, cell) in enumerate(column) {
// MARK: Cell set up
cell.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(cell)
// MARK: Autolayout constraints
// Priorities
cell.setContentHuggingPriority(249, forOrientation: .Horizontal)
cell.setContentHuggingPriority(249, forOrientation: .Vertical)
cell.setContentCompressionResistancePriority(750, forOrientation: .Horizontal)
cell.setContentCompressionResistancePriority(750, forOrientation: .Vertical)
// Horizontal layout
if x == 0 {
container.addConstraint(NSLayoutConstraint(item: cell, attribute: .Leading, relatedBy: .Equal, toItem: container, attribute: .Leading, multiplier: 1, constant: 4))
} else {
container.addConstraint(NSLayoutConstraint(item: cell, attribute: .Leading, relatedBy: .Equal, toItem: board[x - 1][y], attribute: .Trailing, multiplier: 1, constant: 4))
container.addConstraint(NSLayoutConstraint(item: cell, attribute: .Width, relatedBy: .Equal, toItem: board[x - 1][y], attribute: .Width, multiplier: 1, constant: 0))
}
if x == board.count - 1 {
container.addConstraint(NSLayoutConstraint(item: container, attribute: .Trailing, relatedBy: .Equal, toItem: cell, attribute: .Trailing, multiplier: 1, constant: 4))
}
// Vertical layout
if y == 0 {
container.addConstraint(NSLayoutConstraint(item: cell, attribute: .Top, relatedBy: .Equal, toItem: container, attribute: .Top, multiplier: 1, constant: 4))
} else {
container.addConstraint(NSLayoutConstraint(item: cell, attribute: .Top, relatedBy: .Equal, toItem: board[x][y - 1], attribute: .Bottom, multiplier: 1, constant: 4))
container.addConstraint(NSLayoutConstraint(item: cell, attribute: .Height, relatedBy: .Equal, toItem: board[x][y - 1], attribute: .Height, multiplier: 1, constant: 0))
}
if y == board[x].count - 1 {
container.addConstraint(NSLayoutConstraint(item: container, attribute: .Bottom, relatedBy: .Equal, toItem: cell, attribute: .Bottom, multiplier: 1, constant: 4))
}
}
}
但是在运行时,出现以下错误
2014-11-05 17:12:56.333 ProjectName[21373:1094967] Unable to simultaneously satisfy constraints:
(
"<NSLayoutConstraint:0x610000081c70 V:[NSView:0x610000121d60]-(4)-[NSView:0x610000121d60]>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x610000081c70 V:[NSView:0x610000121d60]-(4)-[NSView:0x610000121d60]>
Set the NSUserDefault NSConstraintBasedLayoutVisualizeMutuallyExclusiveConstraints to YES to have -[NSWindow visualizeConstraints:] automatically called when this happens. And/or, break on objc_exception_throw to catch this in the debugger.
现在,board 是一个 NSView 数组,而 NSView 完全是空的。为了得到上面的错误输出,我将board初始化为[[NSView(), NSView()]],即一列两行。
x = 0
------------
board[x][0] | NSView() |
board[x][1] | NSView() |
------------
我的动态布局代码适用于具有任意数量列的单行,但是当给出多于一行时它会由于某种原因而中断。自动布局行的代码与列代码完全相同,对左→上、右→下等进行调整
任何人都知道为什么多行会破坏我的代码?
我正在使用 Xcode 6.1,部署目标为 10.10,快速编程。