Swift - 如何将点击手势添加到 UIViews 数组? [英] Swift - How to add tap gesture to array of UIViews?
问题描述
希望将点击手势添加到 UIView
的数组中 - 没有成功.在此阶段似乎无法识别 Tap.
Looking to add a tap gesture to an array of UIView
s - without success. Tap seems not to be recognised at this stage.
在下面的代码(摘录)中:在主视图上显示一系列 PlayingCardViews
(每个都是一个 UIView
).集合为一个数组:cardView
.需要能够独立点击每个 PlayingCardView
(然后能够识别点击了哪个).
In the code (extract) below:
Have a series of PlayingCardViews
(each a UIView
) showing on the main view.
Brought together as an array: cardView
.
Need to be able to tap each PlayingCardView
independently (and then to be able to identify which one was tapped).
@IBOutlet private var cardView: [PlayingCardView]!
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(tapCard(sender: )))
for index in cardView.indices {
cardView[index].isUserInteractionEnabled = true
cardView[index].addGestureRecognizer(tap)
cardView[index].tag = index
}
}
@objc func tapCard (sender: UITapGestureRecognizer) {
if sender.state == .ended {
let cardNumber = sender.view.tag
print("View tapped !")
}
}
推荐答案
您需要
@objc func tapCard (sender: UITapGestureRecognizer) {
let clickedView = cardView[sender.view!.tag]
print("View tapped !" , clickedView )
}
这里不需要检查状态,因为这种手势类型的方法只被调用一次,而且每个视图都应该有一个单独的点击,所以在 for 循环中创建它
No need to check state here as the method with this gesture type is called only once , also every view should have a separate tap so create it inside the for - loop
for index in cardView.indices {
let tap = UITapGestureRecognizer(target: self, action: #selector(tapCard(sender: )))
这篇关于Swift - 如何将点击手势添加到 UIViews 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!