如何在Swift中设置返回按钮的动作backBarButtonItem?

4
如何设置 action backBarButtonItem 并仍然显示左箭头?
我使用了以下代码,但箭头没有显示。
var barBack = UIBarButtonItem(title: "Reset", style: UIBarButtonItemStyle.Plain, target: self, action: "reset:")
self.navigationItem.leftBarButtonItem = barBack

但是当我使用这段代码时,动作没有起作用。
self.navigationController?.navigationBar.topItem?.backBarButtonItem = barBack

谢谢

3个回答

2
作为设置操作的替代方案,您可以保留backBarButtonItem并使用isMovingFromParentViewController来处理在导航堆栈上返回的逻辑。
override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    if isMovingFromParentViewController() {
        .. do something here
    }
}

0

试试这个

var barBack = UIBarButtonItem(title: "Reset", style: UIBarButtonItemStyle.Plain, target: self, action: "reset:")
self.navigationItem.leftBarButtonItem = barBack

请告诉我它是否有效。


看起来像是我的代码。请仔细阅读我的问题。谢谢。 - Aditya Dharma
实际上有点不同,因为您正在使用导航控制器的导航栏的顶部项目属性,这可能并不总是活动状态,例如当页面未嵌入导航控制器时。另一方面,我正在使用页面navigationItem的leftBarButtonItem。请尝试我的代码并查看是否有效,因为在发布答案之前我已经尝试过了。 - Rajeev Bhatia
我们代码中唯一相同的地方就是barbuttonitem的初始化。 - Rajeev Bhatia

0
尝试这个: 在 ViewDidLoad 中。
    let backButton = UIBarButtonItem(title: "< Home", style: UIBarButtonItemStyle.Plain, target: self, action: "goBack")
    navigationItem.leftBarButtonItem = backButton
    navigationItem.backBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "the_font_you_want_to_use", size: size_of_the_font_this_should_be_integer)!], forState: UIControlState.Normal)

并实现以下方法:

    func goBack() {
    self.navigationController?.popToRootViewControllerAnimated(boolean)
}

只需将 the_font_you_want_to_use、size_of_the_font_this_should_be_integer 和 boolean 替换为您想要的值,一切都会正常工作。

*** 编辑

如果您不想返回到“根视图控制器”,而是

self.navigationController?.popToRootViewControllerAnimated(boolean)

你可以说:

self.navigationController?.popViewControllerAnimated(boolean)

或者甚至可以通过指定 popToViewController 的第一个参数为 YourViewController 类的对象,第二个参数为布尔值来弹出到其他 ViewController


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接