从约束数组中访问特定约束

问题描述 投票:0回答:1

假设你有一系列约束

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]进入顶级锚。在这种情况下,我如何直接访问锚点数组中的顶部锚点?

ios swift nslayoutconstraint
1个回答
1
投票

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

我将顶部约束的标识符设置为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 { $0.identifier == LayoutAnchor.top.rawValue }.first
        case .bottom:
            return self.filter { $0.identifier == LayoutAnchor.bottom.rawValue }.first
        case .left:
            return self.filter { $0.identifier == LayoutAnchor.left.rawValue }.first
        case .right:
            return self.filter { $0.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]
© www.soinside.com 2019 - 2024. All rights reserved.