skip to Main Content

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)
        }
    }
}

enter image description here

I expecting the value of the sender.tag will be 1-8,not always 0

2

Answers


  1. In iOS development, the tag property of a UIButton 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 use sender.tag to achieve this:

    1. Create multiple buttons with different tags:
    let button1 = UIButton()
    button1.tag = 1
    button1.setTitle("Button 1", for: .normal)
    
    let button2 = UIButton()
    button2.tag = 2
    button2.setTitle("Button 2", for: .normal)
    
    1. Add a target and action to the buttons:
    button1.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
    button2.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
    
    1. Implement the action method, which will receive the button as a parameter:
    @objc func buttonTapped
    
    Login or Signup to reply.
  2. 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

    enter image description here

    Programmatically

    yourView.tag = number that you want to have
    

    Reference

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search