Traverse view controller hierarchy in Swift

2019-05-22 18:24发布

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 ?

3条回答
Juvenile、少年°
2楼-- · 2019-05-22 18:42

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
    }
}
查看更多
三岁会撩人
3楼-- · 2019-05-22 18:42

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
    }
}
查看更多
ゆ 、 Hurt°
4楼-- · 2019-05-22 18:51

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? {
  // ....
}
查看更多
登录 后发表回答