use*_*273 3 ios presentviewcontroller swift
当用户单击 tableviewcell 中的元素时,我想呈现一个新的 ViewController。然而,用于启动 VC 的标准代码在 tableview 单元格中不起作用,甚至在助手类中不起作用,因为 TVC 和助手类都无法呈现视图控制器。
这是辅助类中的代码。无论是放置在 helperclass 还是 tableview cell 中,它都没有启动 VC 的当前方法。
class launchVC {
func launchVCNamed(identifier: String) {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let secondVC = storyBoard.instantiateViewController(withIdentifier: "contactDetail")
//FOLLOWING LINE HAS ERROR NO SUCH MEMBER (present)
self.present(secondVC, animated: true, completion: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
我该如何修改它来启动 VC?
通常,您应该使用委托模式或闭包将块从单元传递回视图控制器。我更喜欢对委托使用闭包,所以我将给出这样的例子:
class SomeCell: UITableViewCell {
var actionBlock = { }
func someActionOccured() { // some action like button tap in cell occured
actionBlock()
}
}
Run Code Online (Sandbox Code Playgroud)
在cellForRow视图控制器中,您需要分配闭包
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SomeCell // replace cell identifier with whatever your identifier is
cell.actionBlock = { [unowned self] in
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let secondVC = storyBoard.instantiateViewController(withIdentifier: "contactDetail")
self.present(secondVC, animated: true, completion: nil)
}
return cell
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1386 次 |
| 最近记录: |