user2695433
user2695433

Reputation: 2153

Back Button Left Alignment IOS 9

I am trying to left align back button i.e remove the space on the left of the back arrow . Using a custom back button .

let backButton = UIBarButtonItem(image: UIImage(named: "arrow03"), style: .Plain, target: self, action: "back")

self.navigationController?.navigationBar.tintColor = UIColor.clearColor()
self.navigationItem.backBarButtonItem = backButton

Tried to use negative width for the button as suggested in the below SO link but it didnt work. How to Edit Empty Spaces of Left, Right UIBarButtonItem in UINavigationBar [iOS 7]

Image

enter image description here

https://i.sstatic.net/DrEO2.jpg

Please help.

Upvotes: 3

Views: 3601

Answers (1)

Hasya
Hasya

Reputation: 9898

Refer below code to implement back button on left alignment.

let button: UIButton = UIButton (type: UIButtonType.Custom)
button.setImage(UIImage(named: "imageName"), forState: UIControlState.Normal)
button.addTarget(self, action: "backButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
button.frame = CGRectMake(0, 0, 30, 30)
let barButton = UIBarButtonItem(customView: button)

self.navigationItem.leftBarButtonItem = barButton

Note - Make sure your image has to be plain ( transparent ) background.

func backButtonPressed(btn : UIButton) {

    self.navigationController?.popViewControllerAnimated(true)
}

Swift 4 Code

override func viewDidLoad() {
    super.viewDidLoad()

    let button: UIButton = UIButton (type: UIButtonType.custom)
    button.setImage(UIImage(named: "imageName"), for: UIControlState.normal)
    button.addTarget(self, action: Selector(("backButtonPressed:")), for: UIControlEvents.touchUpInside)
    button.frame = CGRect(x: 0 , y: 0, width: 30, height: 30)

    let barButton = UIBarButtonItem(customView: button)

    self.navigationItem.leftBarButtonItem = barButton
}

func backButtonPressed(btn : UIButton) {

    self.navigationController?.popViewController(animated: true)
}

Upvotes: 6

Related Questions