本文介绍了无法在 CollectionViewCell 的按钮中添加带有参数的目标 (Swift 4)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 CollectionViewCell 中有一个按钮,我想在点击按钮时触发 UIActivityViewController(通过 URL).
There is a button in my CollectionViewCell, I would like to trigger the UIActivityViewController (with an URL passing) when the button tapped.
我正在尝试向 CollectionViewCell 中的按钮添加目标(带参数),但似乎不起作用,这是我的代码:
I'm trying to add a target (with parameter) to the button which is in CollectionViewCell, but it seems it doesn't work, here are my codes:
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)
}
错误是:'#selector' 的参数不引用'@objc' 方法、属性或初始化程序
它在没有参数传递时效果很好,就像这样:
It just works well when no parameters passing, like this:
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)
}
任何建议将不胜感激.
推荐答案
您不能在目标/动作选择器中传递任意参数.
You cannot pass an arbitrary parameter in a target/action selector.
支持的形式是
- 无参数
- 一个必须是动作发送者的参数 (
shareButtonPressed(_ sender: UIButton)
) - 一些
UIControl
项目还允许额外的UIControlEvents
参数.
- No parameter
- One parameter which must be the sender of the action (
shareButtonPressed(_ sender: UIButton)
) - Some
UIControl
items allow also an additionalUIControlEvents
parameter.
这篇关于无法在 CollectionViewCell 的按钮中添加带有参数的目标 (Swift 4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!