Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift 3.0 UIBarButtonItem action not work

let leftbarbuttonitem = UIBarButtonItem(title:"Reset",style: .plain, target: self, action: #selector(tapResetButton(_:)))

    func tapResetButton(_ sender:UIBarButtonItem){
        count = 0
        numberLabel.text = "0"

    }

The action can't respond to the click event. I added the breakpoint then found that it even didn't go into the function. I have no idea what's wrong with my code. Any answer will be appreciated. Thanks in advance.

like image 840
littlebear333 Avatar asked Nov 03 '16 01:11

littlebear333


2 Answers

Swift 3.0

Declare UIBarButton inside ViewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()
    let logout: UIBarButtonItem = UIBarButtonItem.init(title: "Logout", style: .plain, target: self, action: #selector(ViewController.logOut))
}

func logOut() {
  print("LogOut")
}

Declare UIBarButtonItem OutSide ViewDidLoad()

var logout:UIBarButtonItem = UIBarButtonItem()

override func viewDidLoad() {
        super.viewDidLoad()
        logout = UIBarButtonItem.init(title: "Logout", style: .plain, target: self, action: #selector(ViewController.logOut))
}

func logOut() {
      print("LogOut")
}

Declare Completely Outside viewDidLoad()

lazy var logout: UIBarButtonItem = {
    UIBarButtonItem.init(title: "Logout", style: .plain, target: self, action: #selector(ViewController.logOut))
}()

Any Should work.

For your action parameter either you can specify ViewController name explicitly or you can just say self.

action: #selector(self.logOut)
like image 200
Ashok R Avatar answered Nov 13 '22 20:11

Ashok R


When I put the initialization of UIBarButtonItem out of the function viewDidLoad, the action can't respond. But when I put it into the function. It works. I don't know why. But the problem is resolved. If you know the reason. Please tell me. Thank you.

like image 5
littlebear333 Avatar answered Nov 13 '22 20:11

littlebear333