Reputation: 1931
I don't actually get an error, but the buttons don't call the function when they get pressed. I created a class to make my buttons easier but there is an issue with the selector. Right now all this code is in my viewController at the moment.
class NavButton {
var button: UIButton = UIButton(type: UIButtonType.custom)
init(iconName: String, selector: Selector ){
self.button.setImage(UIImage(named: iconName), for: UIControlState.normal)
self.button.addTarget(self, action: selector, for: .touchUpInside)
self.button.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
self.button.imageView?.contentMode = UIViewContentMode.scaleAspectFit
self.button.widthAnchor.constraint(equalToConstant: 20).isActive = true
self.button.heightAnchor.constraint(equalToConstant: 20).isActive = true
}
func construct() -> UIButton {
return self.button
}
}
private func setupNavBar(){
let searchButton = NavButton(iconName:"search_icon", selector: #selector(handleSearch))
let moreButton = NavButton(iconName:"nav_more_icon", selector: #selector(handleMore))
let searchBarButtonItem = UIBarButtonItem(customView: searchButton.construct())
let moreBarButtonItem = UIBarButtonItem(customView: moreButton.construct())
navigationItem.rightBarButtonItems = [
moreBarButtonItem,
searchBarButtonItem
]
}
@objc func handleSearch(){
print("search click")
}
@objc func handleMore(){
print("more click")
}
Upvotes: 2
Views: 60
Reputation: 3008
Pass the target as a parameter into the NavButton class.
init(iconName: String, target: Any?, selector: Selector){
button.setImage(UIImage(named: iconName), for: .normal)
button.addTarget(target, action: selector, for: .touchUpInside)
// Rest of method follows
}
The target should be the object on which the action selector is defined.
Upvotes: 1
Reputation: 270980
Selector
s only represent a method, but they don't represent on which object to call the method i.e. the target.
In your constructor, you set the target to self
:
self.button.addTarget(self, action: selector, for: .touchUpInside)
^^^^^
This means that the button, when pressed will try to call an instance method in the NavButton
class. But you actually want to call the handleSearch
method in some other class!
To fix this, add a target parameter in the constructor:
init(iconName: String, target: Any?, selector: Selector ){
self.button.setImage(UIImage(named: iconName), for: UIControlState.normal)
// note the change to the below line
self.button.addTarget(target, action: selector, for: .touchUpInside)
self.button.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
self.button.imageView?.contentMode = UIViewContentMode.scaleAspectFit
self.button.widthAnchor.constraint(equalToConstant: 20).isActive = true
self.button.heightAnchor.constraint(equalToConstant: 20).isActive = true
}
And then call the constructor like this:
NavButton(iconName:"search_icon", target: self, selector: #selector(handleSearch))
Upvotes: 2