从约束数组访问特定约束

accessing a specific constraint from array of constraints

假设你有一组约束

let constraints = [NSLayoutConstraints]

而且我想使用下标以某种方式访问​​顶部锚点。我试过了

extension Array where Element: NSLayoutConstraint {

enum LayoutAnchor {
    case top
    //case left
    //case bottom
    //case right
}

subscript(anchor: LayoutAnchor) -> NSLayoutConstraint? {
    switch anchor {
    case .top: return self.index(of: topAnchor)
    }
}
}

所以我可以调用 anchors[.top] 访问顶部锚点。在这种情况下,我如何直接访问锚点数组中的顶部锚点?

我不确定你的目标是什么,但你需要以某种方式识别 NSLayoutConstraint

我把top constraint的identifier设置为你的LayoutAnchor类型,那么constraints[.top]就很容易构建了。但这并不安全,因为数组可能包含多个具有相同类型的约束,或者根本不包含。 请注意 constraints[.bottom]nil 因为没有为底部设置标识符。

以下是游乐场的摘录,希望对您有所帮助。

enum LayoutAnchor: String {
    case top
    case left
    case bottom
    case right
}

extension Array where Element: NSLayoutConstraint {
    subscript(anchor: LayoutAnchor) -> NSLayoutConstraint? {
        switch anchor {
        case .top:
            return self.filter { [=10=].identifier == LayoutAnchor.top.rawValue }.first
        case .bottom:
            return self.filter { [=10=].identifier == LayoutAnchor.bottom.rawValue }.first
        case .left:
            return self.filter { [=10=].identifier == LayoutAnchor.left.rawValue }.first
        case .right:
            return self.filter { [=10=].identifier == LayoutAnchor.right.rawValue }.first
        }
    }
}

let view1 = UIView()
let view2 = UIView()

let top = view1.topAnchor.constraint(equalTo: view2.topAnchor)
top.identifier = LayoutAnchor.top.rawValue

let constraints: [NSLayoutConstraint] = [
    top,
    view1.bottomAnchor.constraint(equalTo: view2.bottomAnchor)
]

constraints[.top]
constraints[.bottom]