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

Swift中如何禁用UIToolbar弹性空间的点击触发行为?

解决UIToolbar弹性空间点击触发相邻按钮动作的问题

嘿,我之前也碰到过一模一样的问题!你的问题根源其实特别简单——你重复使用了同一个UIBarButtonItem实例(也就是那个flexibleSpace)多次添加到Toolbar的items数组里。

UIKit里的控件/BarButtonItem实例都有个隐形规则:每个实例只能被添加到父容器一次。当你把同一个flexibleSpace四次塞进setItems的数组里时,Toolbar的内部布局和事件响应系统直接乱套了,点击弹性空间区域时,事件会错误地传递给相邻的按钮,就出现了你看到的“点空白触发快退/快进”的诡异情况。

解决方案:每次需要弹性空间时创建新实例

别再复用同一个flexibleSpace了,而是每次都生成一个全新的UIBarButtonItem实例。你可以这样写:

// 先创建所有功能按钮
let rewind = UIBarButtonItem(barButtonSystemItem: .rewind, target: self, action: #selector(SongsViewController.rewindButton(_:)))
let playPause = UIBarButtonItem(barButtonSystemItem: .play, target: self, action: #selector(SongsViewController.playPauseButton(_:)))
let fastForward = UIBarButtonItem(barButtonSystemItem: .fastForward, target: self, action: #selector(SongsViewController.fastForwardButton(_:)))

// 封装一个快速创建弹性空间的小方法
func makeFlexibleSpace() -> UIBarButtonItem {
    return UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
}

// 组装Toolbar的items数组,每个弹性空间都是独立实例
buttonToolbar.setItems([
    makeFlexibleSpace(),
    rewind,
    makeFlexibleSpace(),
    playPause,
    makeFlexibleSpace(),
    fastForward,
    makeFlexibleSpace()
], animated: false)

额外补充说明

  • 你之前写的flexibleSpace?.isEnabled = false完全没生效,因为这行代码在你创建flexibleSpace实例之前就执行了(此时flexibleSpace还是nil),而且弹性空间本身默认就是不可交互的,根本不需要手动禁用。
  • 至于故事板的问题,大概率不是这里的原因,但你可以顺手检查一下Toolbar有没有额外添加的手势识别器,或者按钮有没有错误的关联——不过根据你的代码,核心问题肯定是复用实例导致的。

试一下上面的代码,应该就能彻底解决你的问题了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:31:30