我有三个视图控制器WebkitViewController
,然后还有两个都扩展了WebkitViewControllerA
的其他两个视图控制器WebkitViewControllerB
和WebkitViewController
。我在编写通用功能时遇到麻烦,该通用功能将查看segue目标的视图控制器并告诉我这是三种类型中的哪一种。有更好的方法吗?
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.destination is WebKitViewController && sender is UIButton {
let viewControllerType = {
if segue.destination is WebKitViewControllerA {
WebKitViewControllerA.self
} else if segue.destination is WebKitViewControllerB {
WebKitViewControllerB.self
} else {
WebKitViewController.self
}
}()
let button = sender as? UIButton
let vc = segue.destination as? viewControllerType
vc?.foo = "ho ho ho"
}
}
}
我也尝试了以下类似方法:
var vc: WHAT_TYPE_TO_PUT_HERE?
if segue.destination is CustomViewController {
vc = segue.destination as? CustomViewController
} else if segue.destination is WebKitBelowFoldViewController {
vc = segue.destination as? WebKitBelowFoldViewController
} else {
vc = segue.destination as? WebKitViewController
}
但是我不知道我可以给vc提供哪种类型的类型检查器。
由于这些都是WebkitViewController的子类,因此vc
将是WebkitViewController。另外,应该没有理由检查每种类型。您需要在这里提供的是:
if let vc = segue.destination as? WebKitViewController {
vc.foo = "ho ho ho"
}