如何使用SWIFT处理导航栏中的BackBarButtonItem单击事件?

时间:2016-02-15 08:18:08

标签: ios swift

按下导航栏后退按钮时,我尝试处理操作。然而我为另一个viewController设置了segue。

当用户点击 5 次后退按钮时,我需要保持计数。为此,我实施了这些东西。

在此我设置了导航栏后退按钮的操作:

class DetailViewController:UIViewController, UITabBarDelegate, UINavigationControllerDelegate{
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.backBarButtonItem?.action = "perform"
        self.navigationController?.delegate = self
    }

    func perform(){
        if count == 5{
            count=0
            print("Back Button pressed 5 times")
        }
    }
}

我在哪里弄错了?

2 个答案:

答案 0 :(得分:1)

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let backItem = UIBarButtonItem(title: "Back", style: .Plain, target: self, action: "tapToBack")
        self.navigationItem.leftBarButtonItem = backItem
    }

    func tapToBack() {
        var times = 0
        times++
        NSLog("tap times:%d", times)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

答案 1 :(得分:0)

这就是应该实施的方式:

override func viewDidLoad {
    super.viewDidLoad()
    self.navigationItem.hidesBackButton = true
    let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Bordered, target: self, action: "back:")
    self.navigationItem.leftBarButtonItem = newBackButton;
}

func back(sender: UIBarButtonItem) {
  // your code
}