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

UIButton的sender.tag始终为0,设置不同标签值仍无效

解决UIButton绑定同一IBAction时tag始终为0的问题

我在Storyboard中添加了多个UIButton,将它们绑定到同一个IBAction方法,但点击按钮时sender.tag的值始终为0,预期该值应为1-8。相关Swift代码如下:

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var player: AVAudioPlayer!
    let sounds = ["note1", "note2", "note3", "note4", "note5", "note6", "note7"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    @IBAction func play(_ sender: UIButton) {
        print(sender.tag)
        play(tag: sender.tag)
    }
    
    // 封装函数
    func play(tag :Int) {
        // 确定文件有就加!
        let url = Bundle.main.url(forResource: sounds[tag], withExtension: "wav")!
        do {
            player = try AVAudioPlayer(contentsOf: url)
            player.play()
        } catch {
            print(error)
        }
    }
}

界面截图:界面截图


解决步骤:

  • 手动设置Storyboard中按钮的Tag值:
    选中每个按钮,打开右侧属性检查器(Attributes Inspector),找到Tag选项,将其设置为1-8对应的数值(注意默认值是0,必须手动修改)。
  • 验证IBAction绑定关系:
    右键点击每个按钮,确认Touch Up Inside事件已正确关联到play(_:)方法,避免绑定错误导致sender信息异常。
  • 检查代码中的Tag重置逻辑:
    排查viewDidLoad或其他生命周期方法,确保没有代码将按钮的Tag值意外重置为0。
  • 修复数组越界风险:
    当前sounds数组仅有7个元素(索引0-6),如果Tag设置为1-8,调用sounds[tag]会触发数组越界崩溃。建议将Tag调整为0-6,或者补充sounds数组元素至8个,匹配Tag范围。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 04:25:00