Swift 判断多个视图控件的交互事件
2016-03-19 本文已影响580人
小黑Swift
使用代码循环创建多个视图进行交互时候,可以通过tag值判断点击的是哪个视图或控件
比如下面3个常用的UI组件,UIImageView 和 UILabel 都是直接继承 UIView的,因为 UIView 又是 UIResponder 子类,这意味着视图是允许用户交互的。创建时候默认是没有打开交互的,所以增加手势事件时候,记得启动用户交互。而UIButton 是进行封装过的,已经默认有点击事件的。其他类似组件可以自己查看官网继承关系进行学习利用。
UIimageView UILabel UIButtonImageView
// ImageView
let imageView = UIImageView()
imageView.tag = i // tag值
imageView.userInteractionEnabled = true //启动用户交互
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(TappedClick))
imageView.addGestureRecognizer(tapGestureRecognizer) //增加点击手势
func imageTapped(recognizer: UITapGestureRecognizer) {
switch recognizer.view!.tag {
case 0...6:
print("\(recognizer.view!.tag)")
default:
break
}
}
Label
// label
let label = UILabel()
label.tag = i // tag值
label.userInteractionEnabled = true //启动用户交互
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(TappedClick))
label.addGestureRecognizer(tapGestureRecognizer) //增加点击手势
func labelTapped(recognizer: UITapGestureRecognizer) {
switch recognizer.view!.tag {
case 0...6:
print("\(recognizer.view!.tag)")
default:
break
}
}
button
// button
let btn = UIButton()
btn.tag = i
btn.addTarget(self, action: "btnClick:", forControlEvents: .TouchUpInside)
func btnClick(sender: UIButton) {
switch sender.tag {
case 0...6:
print("\(sender.tag)")
default:
break
}
}