我有一个 TableViewController、TableViewCell 和一个 ViewController。我在 TableViewCell 中有一个按钮,我想用 presentViewController
呈现 ViewController(但 ViewController 在 Storyboard上没有 View )。我尝试使用:
@IBAction func playVideo(sender: AnyObject) {
let vc = ViewController()
self.presentViewController(vc, animated: true, completion: nil)
}
Error: Value of type TableViewCell has no member presentViewController
然后,我尝试了
self.window?.rootViewController!.presentViewController(vc, animated: true, completion: nil)
Error: Warning: Attempt to present whose view is not in the window hierarchy!
我做错了什么?我应该怎么做才能从 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)
}
I receive error: Presenting view controllers on detached view controllers is discouraged
(请注意,我在 TableView 后面有一个 NavBar 和 TabBar 链。)
我也试过
self.parentViewController!.presentViewController(vc, animated: true, completion: nil)
同样的错误。
也试过了,
self.view.window?.rootViewController?.presentViewController(vc, animated: true, completion: nil)
同样的错误
最佳答案
您似乎已经知道要呈现 View Controller ,您需要一个 View Controller 。因此,您需要执行以下操作:
- 创建一个协议(protocol),通知单元的 Controller 按钮已按下。
- 在您的单元格中创建一个属性,该属性包含对实现您的协议(protocol)的委托(delegate)的引用。
- 在按钮操作内对您的委托(delegate)调用协议(protocol)方法。
- 在您的 View Controller 中实现协议(protocol)方法。
- 配置单元格时,将 View Controller 作为委托(delegate)传递给单元格。
这是一些代码:
// 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
//...
}
//...
}
关于ios - 来自 TableViewCell 的 presentViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34911022/