[英]How to pass variables to function with selector swift 3
I'm trying to pass a variable to a function which is called within a selector but I'm getting the error 'Argument of #selector does not refer to an @objc method' how am I supposed to pass a variable to a function in a selector. 我正在尝试将变量传递给在选择器中调用的函数,但出现错误“ #selector的参数不引用@objc方法”,我应该如何将变量传递给函数选择器。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "compCell", for: indexPath) as! CompCell
// creating the cell
cell.postImage.downloadImage(from: self.winners[indexPath.row].pathToImage)
print(self.winners[indexPath.row].votes)
let num = self.winners[indexPath.row].votes!
cell.votesLabel.text = "\(num) votes"
cell.title.text = self.winners[indexPath.row].title
cell.postID = self.winners[indexPath.row].postID
cell.compID = self.winners[indexPath.row].compID
//tempComp = cell
let tap = UIGestureRecognizer(target: self, action: #selector(caller(_pressed: cell)))
cell.isUserInteractionEnabled = true
cell.addGestureRecognizer(tap)
return cell
}
func caller(_pressed: CompCell) {
isPressed(_pressedCell: _pressed)
}
func isPressed(_pressedCell: CompCell) {
self.selectedComp = _pressedCell
//prepare(for: IndividualCompSegue, sender: <#T##Any?#>)
performSegue(withIdentifier: "IndividualCompSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? IndividualCompViewController {
destination.comp = self.selectedComp
}
}
You can't pass arbitrary values with the action of a UIGestureRecognizer
. 您不能通过UIGestureRecognizer
的操作传递任意值。 An action takes one parameter which is the UIGestureRecognizer
which triggers the action. 一个动作采用一个参数,即触发该动作的UIGestureRecognizer
。
In your case, you can get the cell
which triggered the tap with the view
property of the gesture recognizer. 在您的情况下,您可以使用手势识别器的view
属性获取触发点击的cell
。
func tapHandler(_ recognizer: UITapGestureRecognizer) {
if let cell = recognizer.view as? Compcell {
isPressed(_pressedCell: cell)
}
}
Also, if you want to detect taps, you need to create a UITapGestureRecognizer
: 另外,如果要检测点击,则需要创建UITapGestureRecognizer
:
let tap = UITapGestureRecognizer(target: self, action: #selector(tapHandler))
Instead of using a tap gesture recognizer to detect a selected cell, you can use 您可以使用以下方法来代替使用轻击手势识别器来检测选定的单元格:
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = self.collectionView(collectionView, cellForItemAt: indexPath) as! CompCell
isPressed(_pressedCell: cell)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.