swift2 在Xcode 7更新之后,UIViewController类型的值没有成员topViewController

5kgi1eie  于 2022-11-06  发布在  Swift
关注(0)|答案(2)|浏览(190)

在我更新到Xcode 7之后,我得到了这个错误“类型UIViewController的值没有成员topViewController”。还有其他人遇到过这个错误吗?topViewController不再是UIViewController的一部分了吗?

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.leftBarButtonItem = self.editButtonItem()
    let addButton = UIBarButtonItem(barButtonSystemItem: .Search,
        target: self, action: "addButtonPressed:")
    self.navigationItem.rightBarButtonItem = addButton

    if let split = self.splitViewController {
        let controllers = split.viewControllers
        self.detailViewController =
            controllers[controllers.count-1].topViewController as? ### Error heres
        DetailViewController
    }

    model = Model(delegate: self) // create the Model
    model.synchronize() // tell model to sync its data
    self.navigationController?.toolbarHidden = false;
    self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"Home", style:.Plain, target:nil, action:nil)
}
nfeuvbwi

nfeuvbwi1#

你必须使它显式化,这样它就知道你试图从Swift 2中的UINavigationController获取topViewController

self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController
wz8daaqr

wz8daaqr2#

Simple Do this 

extension UIApplication {
    class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let navigationController = controller as? UINavigationController {
            return topViewController(controller: navigationController.visibleViewController)
        }
        if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return topViewController(controller: selected)
            }
        }
        if let presented = controller?.presentedViewController {
            return topViewController(controller: presented)
        }
        return controller
    }
}

用法

UIApplication.topViewController()

相关问题