You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改UIBarButtonItem的标题文本?

解决UIBarButtonItem点击后切换标题的问题

嘿,这个场景我太熟悉了!你遇到的问题其实是对setTitle(_:for:)方法的使用场景理解有点偏差,咱们直接用更简单的方式就能搞定:

直接修改title属性(最推荐的方式)

你只需要在点击事件里,切换编辑状态的同时,根据tableView.isEditing的值直接给按钮的title属性赋值就行,代码修改后是这样:

@IBOutlet weak var button: UIBarButtonItem! 

@IBAction func pushEdit(_ sender: Any) {
    tableView.setEditing(!tableView.isEditing, animated: true)
    // 根据编辑状态切换按钮标题
    button.title = tableView.isEditing ? "Done" : "Edit"
}

为什么setTitle(_:for:)没生效?

setTitle(_:for:)是用来给按钮的不同交互状态(比如.normal、.highlighted、.disabled)设置对应标题的,而咱们这里是要根据tableView的编辑状态来切换,不是按钮自身的交互状态,所以用这个方法自然达不到预期效果。

另一种思路:通过TableView代理同步状态

如果你想把状态逻辑和按钮点击解耦,也可以借助TableView的编辑代理方法来更新标题:

override func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
    button.title = "Done"
}

override func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
    button.title = "Edit"
}

最后再检查一下你的IBOutlet连接是否正确,确保button确实关联到了导航栏上的那个“Edit”按钮,这也是新手常踩的小坑~

内容的提问来源于stack exchange,提问作者AntonyCatcher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 17:12:28