如何 get/set 将按钮的标题传递给 UIBarButtonItem-customView 构造函数

How to get/set the Title of a button after that was passed into UIBarButtonItem-customView constructor

当我使用 customView 构造函数创建一个 UIBarButtonItem 时,它获得了一个具有特定属性集的 UIButton,我如何在创建 UIBarButtonItem object 之后访问该属性?

var uiBarButtonItem: UIBarButtonItem {
    let button = UIButton(type: .system)
    button.setImage(UIImage(named: "image-name"), for: .normal)
    button.setTitle("My Button Title", for: .normal)
    button.sizeToFit()
    button.addTarget(self, action: #selector(aFuncName), for: .touchUpInside)
    return UIBarButtonItem(customView: button)
}

它应该像下面的伪代码一样工作:

uiBarButtonItem.button.titleLabel.text
// should return "My Button Title"

谢谢!

您需要访问 UIBarButtonItem 的自定义视图 属性。

if let barItem = self.navigationItem.leftBarButtonItem, //Access rightBarButtonItem if you have set right item
   let btn = barItem.customView as? UIButton {

    btn.setTitle("New", for: .normal)
}