Search code examples
swiftxcodehamburger-menu

Error on adding UINavigationbar button with image


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?

Hamburguer Icon

  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]

Solution

  • 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.