如何从交换机案例中获取NSLayoutAnchor?

时间:2017-05-19 03:46:30

标签: swift xcode autolayout nslayoutconstraint

我想做类似的事情:

public enum LayoutEdge
{
    case top
    case right
    ...
}

func anchorForLayoutEdge(_ edge : LayoutEdge) -> NSLayoutAnchor {
    switch edge
    {
    case .top:      return topAnchor
    case .right:    return rightAnchor
    ... 
    }
}

public func constrain_edge(_ edge : LayoutEdge,
                           toEdge : LayoutEdge,
                           view : UIView) -> NSLayoutConstraint{
    let a1 = anchorForLayoutEdge(edge)
    let a2 = anchorForLayoutEdge(toEdge)
    return a1.constraint(equalTo: a2))
}

但是这不能编译。它在anchorForLayoutEdge中失败了。 Xcode建议将返回类型更改为NSLayoutAnchor,这似乎是错误的。我如何才能使其返回正确的NSLayoutXAxisAnchorNSLayoutYAxisAnchor,具体取决于指定的边缘?

1 个答案:

答案 0 :(得分:1)

Swift需要能够在编译时确定类型,但是你尝试返回 NSLayoutAnchor<NSLayoutXAxisAnchor>NSLayoutAnchor<NSLayoutYAxisAnchor>个对象取决于 传递的edge参数。

可以做的是将你的边缘分成与x轴和y轴相关的边缘:

extension UIView
{
    public enum XLayoutEdge {
        case right
        // ...
    }

    public enum YLayoutEdge {
        case top
        // ...
    }

    func anchor(for edge: XLayoutEdge) -> NSLayoutAnchor<NSLayoutXAxisAnchor> {
        switch edge
        {
        case .right: return rightAnchor
        // ...
        }
    }

    func anchor(for edge: YLayoutEdge) -> NSLayoutAnchor<NSLayoutYAxisAnchor> {
        switch edge
        {
        case .top: return topAnchor
        // ...
        }
    }

    public func constrain(edge edge1: XLayoutEdge, to edge2: XLayoutEdge, of view: UIView) -> NSLayoutConstraint {
        return anchor(for: edge1).constraint(equalTo: view.anchor(for: edge2))
    }

    public func constrain(edge edge1: YLayoutEdge, to edge2: YLayoutEdge, of view: UIView) -> NSLayoutConstraint {
        return anchor(for: edge1).constraint(equalTo: view.anchor(for: edge2))
    }

    func useEdges(view: UIView)
    {
        _ = constrain(edge: .right, to: .right, of: view)
        _ = constrain(edge: .top, to: .top, of: view)
    }
}

它会变得更糟,因为你也必须考虑NSLayoutDimension。你可以玩仿制药 但你最终可能会以某种方式复制苹果已经为你准备的内容:)。

这就是我认为你在这里反对系统的原因。退后一步,为什么不直接使用锚点?

extension UIView
{
    func useAnchors(view: UIView)
    {
        _ = rightAnchor.constraint(equalTo: view.rightAnchor)
        _ = topAnchor.constraint(equalTo: view.bottomAnchor)
    }
}

如果您想编写自己的便利功能,可以这样做:

extension UIView
{
    public func constrain<T>(_ anchor1: NSLayoutAnchor<T>, to anchor2: NSLayoutAnchor<T>) -> NSLayoutConstraint {
        return anchor1.constraint(equalTo: anchor2)
    }

    func useYourOwnFunctions(view: UIView)
    {
        _ = constrain(rightAnchor, to: view.rightAnchor)
        _ = constrain(topAnchor, to: view.bottomAnchor)
    }
}