如果用户单击后退按钮,则Swift添加操作

时间:2015-04-15 05:16:16

标签: swift stack warnings

我使用以下代码成功检测用户是否点击了后退按钮:

override func viewWillDisappear(animated: Bool) {
    let viewControllers: NSArray = self.navigationController?.viewControllers as! NSArray
    if viewControllers.indexOfObject(self) == NSNotFound {
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }

    super.viewWillDisappear(animated)
}

但我收到以下警告:

  

来自'[AnyObject]?'不相关的类型'NSArray'总是失败

有没有“整洁”的方法来做到这一点?

3 个答案:

答案 0 :(得分:2)

而不是NSArray,您应该使用Swift数组 - [UIViewController]

已修复问题:

override func viewWillDisappear(animated: Bool) {
        let viewControllers: [UIViewController] = self.navigationController?.viewControllers as [UIViewController]

        if let index = find(viewControllers, self)
        {
            //your object exists in that is at index

        }
        else
        {
           //your object is not in the navigation controller
           self.navigationController?.setNavigationBarHidden(true, animated: true)
        }

    super.viewWillDisappear(animated)
}

您可以使用

代替if let else
if find(viewControllers, self) == nil
{
    //your object isnt in the viewControllers array

}

答案 1 :(得分:0)

基本上问题是你正在尝试强制转换为objective-c数组类型NSArray。 Swift使用Array而不是NSArray / NSMutableArray。如果要在Swift中转换数组,则必须指定数组内的对象类型。所以下面的代码:

let viewControllers: [UIViewController] = self.navigationController?.viewControllers as! [UIViewController]

将其专门转换为UIViewControllers的Array(Swift数组)。你可以把它写得更短,只需要这样:

let viewControllers = self.navigationController?.viewControllers as! [UIViewController]

答案 2 :(得分:0)

请尝试以下代码:

override func viewWillDisappear(animated: Bool) {
    if let viewControllers = navigationController?.viewControllers as? [UIViewController] {
        if let index = find(viewControllers, self) {
            navigationController?.setNavigationBarHidden(true, animated: true)
        }
    }

    viewWillDisappear(animated)
}

根据我的观点,使用find()更符合Swift。如果找到,find()将返回元素的索引,否则返回nil。