Reputation: 760
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.
Upvotes: 14
Views: 11597
Reputation: 20766
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)
Upvotes: 24
Reputation: 760
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.
Upvotes: 5