无法在CollectionViewCell按钮(Swift 4)中添加带参数的目标

时间:2018-03-10 16:13:55

标签: swift uicollectionviewcell addtarget

我的CollectionViewCell中有一个按钮,当按下该按钮时,我想触发UIActivityViewController(带有URL传递)。

我试图将目标(带参数)添加到CollectionViewCell中的按钮,但似乎它不起作用,这是我的代码:

  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: verticalCellId, for: indexPath) as! VerticalCellId

    if let articleURL = self.card?[indexPath.item]._uRLAddress {

    cell.shareButton.addTarget(self, action: #selector(shareButtonPressed(sharedURL: articleURL)), for: .touchUpInside)

   }

}


  @objc func shareButtonPressed(sharedURL: String) {

    let shareText = sharedURL
    let activityViewController : UIActivityViewController = UIActivityViewController(activityItems: [shareText], applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view
    self.present(activityViewController, animated: true, completion: nil)
}

错误是:Argument of '#selector' does not refer to an '@objc' method, property, or initializer

没有参数传递时效果很好,如下所示:

 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: verticalCellId, for: indexPath) as! VerticalCellId

    if let articleURL = self.card?[indexPath.item]._uRLAddress {

    cell.shareButton.addTarget(self, action: #selector(shareButtonPressed), for: .touchUpInside)

   }

}

@objc func shareButtonPressed() {

    let shareText = NSLocalizedString("Share our app with friends.", comment: "share")
    let activityViewController : UIActivityViewController = UIActivityViewController(activityItems: [shareText], applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view
    self.present(activityViewController, animated: true, completion: nil)
}

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:2)

无法在目标/操作选择器中传递任意参数。

支持的表格是

  • 无参数
  • 一个参数必须是操作的发件人(shareButtonPressed(_ sender: UIButton)
  • 某些UIControl项还允许额外的UIControlEvents参数。