如何在 Swift 中获取父 ViewController 的类名? [英] How to get class name of parent ViewController in Swift?

查看:42
本文介绍了如何在 Swift 中获取父 ViewController 的类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在当前(子)UIViewController 中获取父 VC 的类名?我的子"VC(推送)有两个父"UIViewController,所以我想知道哪个是当前父?

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 would like to know which one is current parent?

推荐答案

这是一种方法:

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

首先,分配并可选地解包 self.parentViewController.

First, assign and optionally unwrap self.parentViewController.

其次,使用可选的强制转换as?,如果有效,将视图控制器分配给parentVC.

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.

这篇关于如何在 Swift 中获取父 ViewController 的类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆