关于swift:swift53-UIView-与-UIButton-点击事件传递参数

4次阅读

共计 859 个字符,预计需要花费 3 分钟才能阅读完成。

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)
}
正文完
 0