小编典典

如何从UICollectionViewCell内调用presentViewController

swift

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

错误:

您的单元格没有成员presentViewController

该怎么办?


阅读 366

收藏
2020-07-07

共1个答案

小编典典

UITableViewCell永远不应处理任何业务逻辑。它应该在视图控制器中实现。您应该使用一个委托:

UICollectionViewCell子类:

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

class CustomCell: UITableViewCell {
    var delegate: CustomCellDelegate?

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

ViewController:

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
    }
}
2020-07-07