来自TableViewCell的presentViewController

sen*_*nty 2 uitableview tableview tableviewcell ios swift

我有一个TableViewController,TableViewCell和一个ViewController.我在TableViewCell中有一个按钮,我想要呈现ViewController presentViewController(但是ViewController在storyboard上没有视图).我试过用:

@IBAction func playVideo(sender: AnyObject) {
        let vc = ViewController()
        self.presentViewController(vc, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

错误:TableViewCell类型的值没有成员presentViewController


然后,我试过了

self.window?.rootViewController!.presentViewController(vc, animated: true, completion: nil)

错误:警告:尝试显示其视图不在窗口层次结构中!


我究竟做错了什么?我应该怎么做才能从TableViewCell中呈现ViewController?另外,我如何将数据传递给TableViewCell的新呈现VC?


更新:

protocol TableViewCellDelegate
{
   buttonDidClicked(result: Int)
}

class TableViewCell: UITableViewCell {

    @IBAction func play(sender: AnyObject) {
        if let id = self.item?["id"].int {
            self.delegate?.buttonDidClicked(id)
        }
    }
}
----------------------------------------

// in TableViewController

var delegate: TableViewCellDelegate?
func buttonDidClicked(result: Int) {
    let vc = ViewController()
    self.presentViewController(vc, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:不建议在分离的视图控制器上显示视图控制器

(请注意,我在TableView后面有一个NavBar和TabBar链.)


我也试过了

 self.parentViewController!.presentViewController(vc, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

相同的错误.


也尝试过,

self.view.window?.rootViewController?.presentViewController(vc, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

相同的错误

小智 8

看起来你已经有了提出视图控制器的想法,你需要一个视图控制器.所以这就是你需要做的:

  1. 创建一个协议,通知单元格的控制器按下按钮.
  2. 在单元格中创建一个属性,该属性包含对实现协议的委托的引用.
  3. 在按钮操作内调用代理上的协议方法.
  4. 在视图控制器中实现协议方法.
  5. 配置单元时,将视图控制器作为委托传递给单元.

这是一些代码:

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

        //...
    }
//...
}
Run Code Online (Sandbox Code Playgroud)


Bre*_*eek 7

您应该使用protocol将操作传递回tableViewController

1)protocol在您的单元格类中创建一个

2)让button动作调用你的protocol函数

3)将您cell's protocoltableViewController通过cell.delegate = self

4)在cell's protocol那里实现并添加代码

let vc = ViewController()
self.presentViewController(vc, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)