How to get class name of parent ViewController in Swift?

后端 未结 7 1904
清歌不尽
清歌不尽 2021-02-07 03:27

Is there any way to get class name of parent VC in present (child) UIViewController? My \'child\' VC (push) has two \'parent\'UIViewControllers, so I w

7条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-07 03:53

    First add extension in view controller

    extension UIView {
        var parentViewController: UIViewController? {
            var parentResponder: UIResponder? = self
            while parentResponder != nil {
                parentResponder = parentResponder!.next
                if let viewController = parentResponder as? UIViewController {
                    return viewController
                }
            }
            return nil
        }
    }
    

    Now Use it Like this

    let vc = self.parentViewController
    

    or

    if let parentVC = self.parentViewController {
        if let parentVC = parentVC as? someViewController {
            // parentVC is someViewController
        } else if let parentVC = parentVC as? anotherViewController {
            // parentVC is anotherViewController
        }
    }
    

提交回复
热议问题