swift5.3 UIView 与 UIButton 点击事件传递参数

UIViewUIbutton 点击事件的参数传递;目前我通过 tag 解决了

UIButton 的点击参数传递

设置 UIButtontag,详细见代码

let playButton = UIButton(type: .custom)
playButton.setTitle("开始播放", for: .normal)
playButton.backgroundColor = UIColor(white: 1.0, alpha: 0.8)
playButton.layer.cornerRadius = 17.5

// 关键在这一行
playButton.tag = index 

playButton.addTarget(self, action: #selector(playClicked(button:)), for: .touchUpInside)
itemView.addSubview(playButton)

接收


@objc func playClicked(button: UIButton){
    print(button.tag)
}

UIView 的点击事件与传输传递

UIView 是没有点击事件这个东西的,不过我们可以用 UITapGestureRecognizer 手势来解决

详细见代码

let itemView = UIView()
itemView.isUserInteractionEnabled = true

itemView.tag = index  // 传输传递

// 创建手势
let tap = UITapGestureRecognizer(target: self, action:#selector(tapClick(sender:)))

// 添加到 UIView 上
itemView.addGestureRecognizer(tap)
homeMusicScrollView.addSubview(itemView)

接收

同样的道理


@objc func tapClick(sender: UIGestureRecognizer){
    let itemView = sender.view!
    print(itemView.tag)
}