0

我的 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)
}

任何建议将不胜感激。

4

1 回答 1

2

不能在目标/动作选择器中传递任意参数。

支持的形式是

  • 无参数
  • 一个参数,必须是动作的发送者 ( shareButtonPressed(_ sender: UIButton))
  • 有些UIControl项目还允许附加UIControlEvents参数。
于 2018-03-10T16:19:43.740 回答