how to call presentViewController from within a UICollectionViewCell

ios, swift

Solution

UITableViewCell should never handle any business logic. It should be implemented in a view controller. You should use a delegate:

UICollectionViewCell subclass:

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

Problem

calling this function from a `UIViewController` results in no problems, but calling it from a `UICollectionViewCell` raises a pre-compilation error Function : ``` 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) } } ``` Error : your cell has no member presentViewController what to do?

Original source