如何使用选择器swift 3将变量传递给函数

时间:2017-05-09 01:01:55

标签: ios swift swift3

我试图将一个变量传递给一个在选择器中调用的函数,但是我得到了错误' #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
    }
}

1 个答案:

答案 0 :(得分:1)

您无法通过UIGestureRecognizer的操作传递任意值。一个动作需要一个参数,即触发动作的UIGestureRecognizer

在您的情况下,您可以使用手势识别器的cell属性获取触发点按的view

func tapHandler(_ recognizer: UITapGestureRecognizer) {
    if let cell = recognizer.view as? Compcell {
        isPressed(_pressedCell: cell)
    }
}

此外,如果您想检测点按,则需要创建UITapGestureRecognizer

let tap = UITapGestureRecognizer(target: self, action: #selector(tapHandler))

您可以使用

,而不是使用点击手势识别器来检测选定的单元格
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = self.collectionView(collectionView, cellForItemAt: indexPath) as! CompCell
    isPressed(_pressedCell: cell)      
}