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

标签 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"

谢谢!

最佳答案

您需要访问 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)
}

关于swift3 - 如何在传递到 UIBarButtonItem-customView 构造函数后获取/设置按钮的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42959674/

相关文章:

ios - 更改导航栏上 UIButton 的标题,瞬间 iOS 出现错误标题

swift - ImageView - 在启动屏幕上的所有设备上居中对齐图像

ios - 蜂窝数据的可达性测试

ios - 如何从具有图像的自定义栏按钮项目中删除右填充/边距/空间?

Swift 3 - 重新加载 NavigationController 按钮图像

iphone - 如何隐藏导航栏的 uibarbutton 项目

swift - iOS 上带有倾斜文本的 UILabel

swift - 如何指定输出可执行文件的名称?

ios - 命令因信号 : Segmentation fault: 11 while archiving 而失败

ios - 使用外观代理仅定位顶部导航栏的栏按钮