Traverse view controller hierarchy in Swift

核能气质少年 提交于 2020-01-02 07:31:18

问题


I would like to traverse the view controller hierarchy in Swift and find a particular class. Here is the code:

extension UIViewController{

    func traverseAndFindClass<T : UIViewController>() -> UIViewController?{

        var parentController = self.parentViewController as? T?
                                    ^
                                    |
                                    |
        // Error: Could not find a user-defined conversion from type 'UIViewController?' to type 'UIViewController'
        while(parentController != nil){

            parentController = parentController!.parentViewController

        }

        return parentController

    }

}

Now, I know that the parentViewController property returns an optional UIViewController, but I do not know how in the name of God I can make the Generic an optional type. Maybe use a where clause of some kind ?


回答1:


Your method should return T? instead of UIViewController?, so that the generic type can be inferred from the context. Checking for the wanted class has also to be done inside the loop, not only once before the loop.

This should work:

extension UIViewController{

    func traverseAndFindClass<T : UIViewController>() -> T? {

        var currentVC = self
        while let parentVC = currentVC.parentViewController {
            if let result = parentVC as? T {
                return result
            }
            currentVC = parentVC
        }
        return nil
    }
}

Example usage:

if let vc = self.traverseAndFindClass() as SpecialViewController? {
    // ....
}

Update: The above method does not work as expected (at least not in the Debug configuration) and I have posted the problem as a separate question: Optional binding succeeds if it shouldn't. One possible workaround (from an answer to that question) seems to be to replace

if let result = parentVC as? T { ...

with

if let result = parentVC as Any as? T { ...

or to remove the type constraint in the method definition:

func traverseAndFindClass<T>() -> T? {

Update 2: The problem has been fixed with Xcode 7, the traverseAndFindClass() method now works correctly.


Swift 4 update:

extension UIViewController{

    func traverseAndFindClass<T : UIViewController>() -> T? {
        var currentVC = self
        while let parentVC = currentVC.parent {
            if let result = parentVC as? T {
                return result
            }
            currentVC = parentVC
        }
        return nil
    }
}



回答2:


One liner solution (using recursion), Swift 4.1+:

extension UIViewController {
  func findParentController<T: UIViewController>() -> T? {
    return self is T ? self as? T : self.parent?.findParentController() as T?
  }
}

Example usage:

if let vc = self.findParentController() as SpecialViewController? {
  // ....
}



回答3:


Instead of while loops, we could use recursion (please note that none of the following code is thoroughly tested):

// Swift 2.3

public extension UIViewController {

    public var topViewController: UIViewController {
        let o = topPresentedViewController
        return o.childViewControllers.last?.topViewController ?? o
    }

    public var topPresentedViewController: UIViewController {
        return presentedViewController?.topPresentedViewController ?? self
    }
}

On the more general issue of traversing the view controller hierarchy, a possible approach is to have two dedicated sequences, so that we can:

for ancestor in vc.ancestors {
    //...
}

or:

for descendant in vc.descendants {
    //...
}

where:

public extension UIViewController {

    public var ancestors: UIViewControllerAncestors {
        return UIViewControllerAncestors(of: self)
    }

    public var descendants: UIViewControllerDescendants {
        return UIViewControllerDescendants(of: self)
    }
}

Implementing ancestor sequence:

public struct UIViewControllerAncestors: GeneratorType, SequenceType {
    private weak var vc: UIViewController?

    public mutating func next() -> UIViewController? {
        guard let vc = vc?.parentViewController ?? vc?.presentingViewController else {
            return nil
        }
        self.vc = vc
        return vc
    }

    public init(of vc: UIViewController) {
        self.vc = vc
    }
}

Implementing descendant sequence:

public struct UIViewControllerDescendants: GeneratorType, SequenceType {
    private weak var root: UIViewController?
    private var index = -1
    private var nextDescendant: (() -> UIViewController?)? // TODO: `Descendants?` when Swift allows recursive type definitions

    public mutating func next() -> UIViewController? {
        if let vc = nextDescendant?() {
            return vc
        }
        guard let root = root else {
            return nil
        }
        while index < root.childViewControllers.endIndex - 1 {
            index += 1
            let vc = root.childViewControllers[index]
            var descendants = vc.descendants
            nextDescendant = { return descendants.next() }
            return vc
        }
        guard let vc = root.presentedViewController where root === vc.presentingViewController else {
            return nil
        }
        self.root = nil
        var descendants = vc.descendants
        nextDescendant = { return descendants.next() }
        return vc
    }

    public init(of vc: UIViewController) {
        root = vc
    }
}


来源:https://stackoverflow.com/questions/25828147/traverse-view-controller-hierarchy-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!