Reputation: 2882
I am trying to add a Cancel
UIBarButtonItem to my navigation bar using following code:
func setupNavBar() {
self.navBar = UINavigationBar(frame: CGRectMake(0.0, 0.0, UIScreen.mainScreen().bounds.width, 64.0))
let customNavigationItem = UINavigationItem(title: "Connect Accounts")
let cancelButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "cancelClicked")
customNavigationItem.setLeftBarButtonItem(cancelButton, animated: true)
self.navBar.setItems([customNavigationItem], animated: true)
self.view.addSubview(self.navBar)
}
The bar button is appearing completely sticked to the screen edge as follow:
Why is this button appearing sticked to the edge of screen and how can I give it spacing so that it does not sticks there? Please help!
EDIT: My button is sticked to just left edge of screen and not to the top-left corner.
Upvotes: 3
Views: 633
Reputation: 1199
Try it.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.setupNavBar()
}
func setupNavBar() {
let navBar = UINavigationBar(frame: CGRectMake(0.0, 0.0, UIScreen.mainScreen().bounds.width, 64.0))
let customNavigationItem = UINavigationItem(title: "Connect Accounts")
let cancelButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "cancelClicked:")
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
fixedSpace.width = 10
customNavigationItem.leftBarButtonItems = [fixedSpace, cancelButton]
navBar.setItems([customNavigationItem], animated: true)
self.view.addSubview(navBar)
}
func cancelClicked(sender: AnyObject){
print("Good luck!")
}
Upvotes: 0
Reputation: 3088
The correct way to add space is using .FixedSpace :
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
fixedSpace.width = 10
customNavigationItem.leftBarButtonItems = [fixedSpace, cancelButton]
UIBarButtonSystemItemFixedSpace
Blank space to add between other items. Only the width property is used when this value is set.
Available in iOS 2.0 and later.
Upvotes: 1
Reputation: 2617
Try this
let btn = UIButton(frame: CGRectMake(<your margin>, 0, 50, 44))
btn.setTitle("Cancel", forState: UIControlStateNormal)
let btnbarButton = UIBarButtonItem(customView: btn)
customNavigationItem.setLeftBarButtonItem(btnbarButton, animated: true)
Upvotes: 0