添加带有图像的UINavigationbar按钮时出错

时间:2018-06-21 02:01:59

标签: swift xcode hamburger-menu

我正在尝试在UINavigationbar上添加带有图像的UIBarbutton。但是,按钮移动到中心而不是保持在左侧,因此图像也变得很大。你们能帮我吗?

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]

1 个答案:

答案 0 :(得分:0)

自定义左键按钮图片:

    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
  

还要检查要为左栏设置的图像尺寸   按钮。   我将35 x 35用于2x图像,将53 x 53尺寸用于3x图像。