presentViewController from TableViewCell

前端 未结 4 1979

I have a TableViewController, TableViewCell and a ViewController. I have a button in the TableViewCell and I want to present ViewController with presentViewController<

4条回答
  •  既然无缘
    2020-12-17 05:51

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

提交回复
热议问题