Rohan Sanap
Rohan Sanap

Reputation: 2882

Space issue with UIBarButtonItem

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:

enter image description here

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

Answers (3)

Sankalap Yaduraj Singh
Sankalap Yaduraj Singh

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

Yunus Eren Güzel
Yunus Eren Güzel

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

techloverr
techloverr

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

Related Questions