Back Button Left Alignment IOS 9

大憨熊 提交于 2019-12-23 17:03:36

问题


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

http://imgur.com/PA9HLBm

Please help.


回答1:


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)
}


来源:https://stackoverflow.com/questions/36709220/back-button-left-alignment-ios-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!