使用此代码:
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "WhiteBackButton.png"), for: UIControlState.normal)
button.addTarget(self, action:#selector(self.backButtonSelected), for: UIControlEvents.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
let barButton = UIBarButtonItem.init(customView: button)
self.navigationItem.leftBarButtonItem = barButton
如何阻止它从左侧推得太远?
答案 0 :(得分:1)
让negativeSpacer:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.fixedSpace,target:nil,action:nil) negativeSpacer.width = -10 self.navigationItem.leftBarButtonItems = [negativeSpacer,leftBarButton]
答案 1 :(得分:0)
WhiteBackButton.png图片很可能在箭头前方/前方有空白区域。
我建议也使用:
UIBarButtonItem(image:style:target:action :)而不是UIButton,它将简化您的代码......
https://developer.apple.com/reference/uikit/uibarbuttonitem/1617163-init
如果要更改barButtonItems,可以使用以下函数扩展ViewController,并将它们添加到viewWillAppear:
//should have a left and right of each:
func addRightBarButtonWithImage(_ buttonImage: UIImage) {
let rightButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.toggleRight))
navigationItem.rightBarButtonItem = rightButton
}
func setNavigationBarItem() {
self.addLeftBarButtonWithImage(UIImage(named: “icon.png”)!)
self.addRightBarButtonWithImage(UIImage(named: “icon.png”)!)
}
希望这有帮助!干杯!