presentViewController from TableViewCell

最后都变了- 提交于 2019-11-29 05:20:10

You should use protocol to pass the action back to tableViewController

1) Create a protocol in your cell class

2) Make the button action call your protocol func

3) Link your cell's protocol in tableViewController by cell.delegate = self

4) Implement the cell's protocol and add your code there

let vc = ViewController()
self.presentViewController(vc, animated: true, completion: nil)

It seems like you've already got the idea that to present a view controller, you need a view controller. So here's what you'll need to do:

  1. Create a protocol that will notify the cell's controller that the button was pressed.
  2. Create a property in your cell that holds a reference to the delegate that implements your protocol.
  3. Call the protocol method on your delegate inside of the button action.
  4. Implement the protocol method in your view controller.
  5. When configuring your cell, pass the view controller to the cell as the delegate.

Here's some code:

// 1.
protocol PlayVideoCellProtocol {
    func playVideoButtonDidSelect()
}

class TableViewCell {
// ...

// 2.
var delegate: PlayVideoCellProtocol!

// 3.
@IBAction func playVideo(sender: AnyObject) {
    self.delegate.playVideoButtonDidSelect()
}

// ...
}


class TableViewController: SuperClass, PlayVideoCellProtocol {

// ...

    // 4.
    func playVideoButtonDidSelect() {
        let viewController = ViewController() // Or however you want to create it.
        self.presentViewController(viewController, animated: true, completion: nil)
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath: NSIndexPath) -> UITableViewCell {
        //... Your cell configuration

        // 5.
        cell.delegate = self

        //...
    }
//...
}

So self.presentViewController is a method from the ViewController. The reason you are getting this error is because the "self" you are referring is the tableViewCell. And tableViewCell doesn't have method of presentViewController.

I think there are some options you can use: 1.add a delegate and protocol in the cell, when you click on the button, the IBAction will call

self.delegate?.didClickButton()

Then in your tableVC, you just need to implement this method and call self.presentViewController

2.use a storyboard and a segue In the storyboard, drag from your button to the VC you want to go.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!