在传递到UIBarButtonItem-customView构造函数之后,如何获取/设置按钮的标题

时间:2017-03-22 18:14:52

标签: swift3 uibarbuttonitem

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

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"

谢谢!

1 个答案:

答案 0 :(得分:2)

您需要访问UIBarButtonItem

的customView属性
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)
}