I take some UIButton on a storyboard,then i bind these Button with a IBAction function,but the value of sender.tag
always 0
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)
}
}
}
I expecting the value of the sender.tag
will be 1-8,not always 0
2
Answers
In iOS development, the
tag
property of aUIButton
can be used to identify which button was tapped when the same action method is used for multiple buttons. Here’s an example of how you can usesender.tag
to achieve this:By default Apple set
0
as tag to all views. If you want to set, you have to mention them in the storyboard or programmatically.Storyboard/ xib file
Programmatically
Reference