我想做些类似的事情:

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))
}

但这并不能编译。它在节目主持人的安排上失败了。Xcode建议将返回类型更改为NSLayoutAnchor,这似乎是错误的。如何使其根据指定的边返回正确的NSLayoutXAxisAnchorNSLayoutYAxisAnchor

最佳答案

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)
    }
}

关于swift - 如何从开关盒中获取NSLayoutAnchor?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44061108/

10-11 05:35