如何从UICollectionViewCell中调用presentViewController [英] how to call presentViewController from within a UICollectionViewCell

查看:733
本文介绍了如何从UICollectionViewCell中调用presentViewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

UIViewController 调用此函数会导致没有问题,但是从 UICollectionViewCell 调用它会引发一个前编译错误

calling this function from a UIViewController results in no problems, but calling it from a UICollectionViewCell raises a pre-compilation error

功能:

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

your cell has no member presentViewController

怎么办?

推荐答案

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

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

UICollectionViewCell子类:

UICollectionViewCell subclass:

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

class CustomCell: UITableViewCell {
    var delegate: CustomCellDelegate?

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

ViewController:

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

这篇关于如何从UICollectionViewCell中调用presentViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆