首页 > 解决方案 > 获取呈现视图控制器的名称

问题描述

我有一个视图控制器和一个表格视图单元格。它在故事板之外是一个单独的 .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(),但试图弄清楚是否有更好的方法可以通过单击按钮来获取呈现视图控制器?

标签: iosswift

解决方案


据我了解你的问题。您想在用户点击按钮时呈现一个新的视图控制器,该按钮在单元格 ( 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
    }
}

更多关于委托设计模式

另一个很好的阅读


推荐阅读