ios - 获取呈现视图控制器的名称
问题描述
我有一个视图控制器和一个表格视图单元格。它在故事板之外是一个单独的 .xib 文件。在视图控制器中,我注册了 xib/nib,然后cellForRowAtIndexPath
按如下方式使用它:
if (indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 4) {
if let cell = tableView.dequeueReusableCell(withIdentifier: "myCustomCell") as? MyCustomCell {
return cell
}
}
private func registerNibs() {
tableView.register(UINib(nibName: "MyCustomCellView", bundle: nil), forCellReuseIdentifier: "myCustomCell")
}
此单元格有一个按钮,单击该按钮可将应用程序导航到不同的视图控制器。为此,我想要用户单击按钮时呈现视图控制器的名称。
我可以使用UIApplication.shared.topMostViewController()
,但试图弄清楚是否有更好的方法可以通过单击按钮来获取呈现视图控制器?
解决方案
据我了解你的问题。您想在用户点击按钮时呈现一个新的视图控制器,该按钮在单元格 ( MyCustomCell
) 中定义。
如果是这样,有很多很好的方法可以做到这一点,下面给出其中一种
委托设计模式
委托是一种设计模式,它使类或结构能够将其某些职责移交(或委托)给另一种类型的实例。
1. 创建协议MyCustomCellDelegate
protocol MyCustomCellDelegate: class {
func didTap(customCell: MyCustomCell)
}
// Assuming it is the class which inherit from UITableViewCell
class MyCustomCell: UITableViewCell {
// Declare a public property so that you can set it from outside while initializing the cell
weak var delegate: MyCustomCellDelegate?
//function which will be called as soon user taps on the button
@IBAction func didUserTapped() {
delegate?.didTap(customCell: self)
}
}
确认协议
您想在哪里收听按钮触摸事件。在您的情况下,它是一个 Viewcontroller (假设它的名称是HomeViewController
),它具有UITableView
, 应该确认MyCustomCellDelegate
协议。
class HomeViewController: UIViewController, UITableViewDatasource, UITableViewDelegate, MyCustomCellDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 4) {
if let cell = tableView.dequeueReusableCell(withIdentifier: "myCustomCell") as? MyCustomCell {
// Set the delegate, so that whenever user tap on button you can get the callback on the confirming class (for your case it is Current viewcontroller)
cell.delegate = self
return cell
}
}
}
//Define the delegate function which will be called once user tap on a button
func didTap(customCell: MyCustomCell) {
// Here you can write the logic to present/push the new view controller accordingly
}
}
推荐阅读
- operating-system - 计算机在“sti”指令后重新启动
- css - 酒吧看起来不错。动画为什么不行?
- javascript - Animate 不适用于 React 中的 whileHover
- c - 这段代码的输出是什么并有解释?
- mongoose - 错误ConnectorError:未找到连接器“strapi-hook-mongoose”:找不到模块“strapi-connector-strapi-hook-mongoose”
- java - 查找斐波那契数的最后 5 位的算法
- python - 在pygame中球不会从屏幕上反弹
- javascript - JSF 2.3 onmessage 监听器函数未触发
- angular - 试图用 ngcc 备份文件覆盖 @angular/cdk/stepper/step-header.d.ts.__ivy_ngcc_bak,这是不允许的
- kubernetes - 节点未准备好时发送松弛通知的最佳方式?