后退按钮左对齐IOS 9

时间:2016-04-19 05:21:14

标签: ios swift uinavigationbar

我试图左后对齐按钮删除后箭头左侧的空格。使用自定义后退按钮。

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

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

尝试使用按钮的负宽度,如下面的SO链接所示,但它没有用。 How to Edit Empty Spaces of Left, Right UIBarButtonItem in UINavigationBar [iOS 7]

图片

enter image description here

http://imgur.com/PA9HLBm

请帮忙。

1 个答案:

答案 0 :(得分:6)

请参阅下面的代码以实现左对齐的后退按钮。

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

注意 - 确保您的图片必须是普通(透明)背景。

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