Error on adding UINavigationbar button with image

走远了吗. 提交于 2019-12-13 03:01:48

问题


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

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