I used the following tutorial to programmatically create a UIBarButtonItem in Swift, but the icon isn't properly aligned to the border. Here's the code for the button. Can anyone tell me how to modify the code below to properly align the UIBarButtonItem Image?
The 1st image shows the location of the programmatically created uibarbuttonitem, and the 2nd image shows the uibarbuttonitem created from storyboard. I want the programmatically created uibarbuttonitem to look like uibarbuttonitem created using storyboard. Thanks for the help!
var button: UIButton = UIButton()
button.setImage(UIImage(named: "leftArrow.png"), forState: .Normal)
button.frame = CGRectMake(0, 0, 40, 40)
button.targetForAction("actioncall:", withSender: nil)
var leftBarButtonItem:UIBarButtonItem = UIBarButtonItem()
leftBarButtonItem.customView = button
self.navigationItem.leftBarButtonItem = leftBarButtonItem
Also, how do I properly set the action for when the uibarbuttontiem is pressed? I tried the following but it's never called.
func actioncall(sender: AnyObject){
println("action")
}
Edit 1: I updated the code as follows thanks to agy's response.
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
if (cond){
var button: UIButton = UIButton()
button.setImage(UIImage(named: "leftArrow.png"), forState: .Normal)
button.frame = CGRectMake(0, 0, 40, 40)
button.addTarget(self, action: "actioncall:", forControlEvents: .TouchUpInside)
var leftBarButtonItem:UIBarButtonItem = UIBarButtonItem()
leftBarButtonItem.customView = button
var negativeSpacer:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
negativeSpacer.width = -20; // set the value you need
self.navigationItem.leftBarButtonItems = [negativeSpacer,leftBarButtonItem]
}
}
func actioncall(sender: UIButton!){
println("action")
}
but the action still fails. The app crashes when I press the uibarbuttontiem and I get the following error message
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AppName.ProfileViewController actioncall:]: unrecognized selector sent to instance 0x7a07a470'
What's the correct function for the action?
Edit 2: The actioncall is in the same class as where I'm creating the UIBarButtonItem. I'm setting the leftbarbutton on viewwillappear because depending on who views this viewcontroller, the option to go back will replace the previous option located on the leftbarbutton.