问题
I'm trying to add an UIBarbutton with image on my UINavigationbar. However, the button moves to the center instead of keep on the left, also the image becomes huge. Can you guys help me, please?
override func viewDidLoad() {
super.viewDidLoad()
//Delegate TableView
self.tableViewTopSell.delegate = self
//SetupNavBarCustom
self.navigationController?.navigationBar.CustomNavigationBar()
let logo = UIImage(named: "tag.png")
let imageView = UIImageView(image:logo)
self.navigationItem.titleView = imageView
//Hamburg Menu
self.navigationItem.leftBarButtonItem = nil
let button = UIButton(type: .custom)
button.setImage(UIImage (named: "hamburgIcon"), for: .normal)
button.frame = CGRect(x: 0.0, y: 0.0, width: 35.0, height: 35.0)
//button.addTarget(target, action: nil, for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: button)
self.navigationItem.leftBarButtonItems = [barButtonItem]
回答1:
Custom Left-bar button image :
let btnBack = UIButton()
btnBack.setImage(#imageLiteral(resourceName: "back"), for: .normal)
btnBack.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
btnBack.addTarget(self, action: #selector(addTapped), for: .touchUpInside)
btnBack.imageView?.contentMode = .scaleAspectFit
let leftBack = UIBarButtonItem.init(customView: btnBack)
navigationItem.leftBarButtonItem = leftBack
Also check the size of image which you are trying to set for left-bar button. I used 35 x 35 for 2x image and 53 x 53 size for 3x image.
来源:https://stackoverflow.com/questions/50959329/error-on-adding-uinavigationbar-button-with-image