自定义leftBarButtonItem未在Swift 4中显示

时间:2018-08-22 06:07:49

标签: ios swift uinavigationbar

我正在尝试在导航项中添加自定义lefBarButton 但它什么也没显示 我尝试了这些答案

https://stackoverflow.com/questions/48564480/custom-leftbarbuttonitem-not-showed-in-ios-11

navigation bar button not showing in swift 3

navigation bar button and items not showing in swift 3

Navigation bar button not showing

Bar button item not shown in navigationBar

Navigation bar not showing iOS swift

Swift 3 - Why is my Navigation Bar not showing?

iOS 8 Swift navigation bar title, buttons not showing in tab based application

我的视图控制器的搜索类型为show。

这是我的代码

    let leftButton = UIButton(type: .roundedRect)
    leftButton.addTarget(self, action: #selector(backClick), for: .touchUpInside)
    leftButton.setTitle("", for: .normal)
    leftButton.tintColor = UIColor.red
    leftButton.imageView?.image = UIImage(named: "back-icon")
    leftButton.frame = CGRect(x: 0, y: 0, width: 22, height: 15)
    self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: leftButton)

我花了几个小时来修复它。 没有人有任何想法。

enter image description here

这是后退按钮 enter image description here

1 个答案:

答案 0 :(得分:2)

问题出在这一行。

leftButton.imageView?.image = UIImage(named: "back-icon")
  

imageView是只读属性。

如果要设置图像,则应这样设置。

leftButton.setImage(UIImage("back-icon"), for: .normal) // Make sure your image is actually named "back-icon"