How to get class name of parent ViewController in Swift?

后端 未结 7 1882
清歌不尽
清歌不尽 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 04:01

    Here's one approach:

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

    First, assign and optionally unwrap self.parentViewController.

    Second, use optional casting as?, and assign the view controller to parentVC if it works.

    That said, this is a code smell - child view controllers should typically have no idea who their parent view controllers are. Whatever problem you're solving, you should probably solve it with tell, don't ask and delegation instead.

提交回复
热议问题