3

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.stack.imgur.com/DrEO2.jpg

Please help.

Community
  • 1
  • 1
user2695433
  • 2,013
  • 4
  • 25
  • 44
  • beacuse in example they are assigning to leftbarbutton instead of backBarButton . i think you should try answer 2 in this http://stackoverflow.com/questions/36114423/use-default-back-button-in-navigation-controller/36114624#36114624. if you want same image on back bar button for every controller. – Sahil Apr 19 '16 at 05:53
  • thanks @SahilBeri let me try – user2695433 Apr 19 '16 at 05:56

1 Answers1

6

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)
}
Hasya
  • 9,792
  • 4
  • 31
  • 46