如何从UICollectionViewCell中调用presentViewController

时间:2016-10-18 15:03:09

标签: ios 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

该怎么办?

2 个答案:

答案 0 :(得分:13)

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

答案 1 :(得分:1)

这是因为presentViewControllerUIViewController方法,UITableViewCell没有名为presentViewController的方法。

  

该怎么办?

您可以使用Delegation模式来处理按钮的操作(如@alexburtnik答案),或者 - 为了节省一些额外的工作 - 我建议通过tag识别它来处理viewController中单元格按钮的操作。

注意:Swift 3 Code。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! TableViewCell

        cell.myButton?.tag = indexPath.row
        cell.myButton?.addTarget(self, action: #selector(), for: .touchUpInside)

        return cell
    }

    func namesIsTapped(tappedButton: UIButton) {
        // get the user (from users array for example) by using the tag, for example:
        let currentUser = users[tappedButton.tag]

        // do whatever you want with this user now...

    }

希望有所帮助。

相关问题