gpt4 book ai didi

ios - 如何从 UICollectionViewCell 中调用presentViewController

转载 作者:行者123 更新时间:2023-11-30 11:06:17 32 4
gpt4 key购买 nike

UIViewController 调用此函数不会出现任何问题,但从 UICollectionViewCell 调用它会引发预编译错误

功能:

func didTapShare(sender: UIButton)
{
let textToShare = "Swift is awesome! Check out this website about it!"

if let myWebsite = NSURL(string: "http://www.google.com/")
{
let objectsToShare = [textToShare, myWebsite]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)

activityVC.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList]

activityVC.popoverPresentationController?.sourceView = sender
self.presentViewController(activityVC, animated: true, completion: nil)
}
}

错误:

your cell has no member presentViewController

要做什么?

最佳答案

UITableViewCell 永远不应该处理任何业务逻辑。它应该在 View Controller 中实现。您应该使用委托(delegate):

UICollectionViewCell 子类:

protocol CustomCellDelegate: class {
func sharePressed(cell: MyCell)
}

class CustomCell: UITableViewCell {
var delegate: CustomCellDelegate?

func didTapShare(sender: UIButton) {
delegate?.sharePressed(cell: self)
}
}

View Controller :

class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!

//...

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CustomCell
cell.delegate = self
return cell
}
}

extension TableViewController: CustomCellDelegate {
func sharePressed(cell: CustomCell) {
guard let index = tableView.indexPath(for: cell)?.row else { return }
//fetch the dataSource object using index
}
}

关于ios - 如何从 UICollectionViewCell 中调用presentViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52682416/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com