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

如何修改UIButton的TitleLabel?UITableView编辑按钮文字切换问题

解决UITableView编辑按钮标题切换问题

直接修改titleLabel?.text无法正确更新按钮标题,因为UIButton的标题是基于状态管理的,正确做法是使用setTitle(_:for:)方法设置对应状态下的标题。

修改后的代码如下:

@IBAction func editButtonPressed(_ sender: UIButton) {
    // 切换表格编辑状态
    tableView.isEditing.toggle()
    
    // 根据编辑状态设置按钮标题
    let targetTitle = tableView.isEditing ? "Done" : "Edit"
    sender.setTitle(targetTitle, for: .normal)
}

说明

  • setTitle(_:for:)是UIButton官方推荐的标题设置方式,它会自动处理不同状态(如普通、高亮)下的标题显示,确保UI更新生效。
  • 使用toggle()替代!操作符,让状态切换的代码更简洁直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 13:45:28