【问题标题】:Getting name of presenting view controller获取呈现视图控制器的名称
【发布时间】:2020-05-20 17:10:49
【问题描述】:

我有一个视图控制器和一个表格视图单元格。在它上面有一个独立的 .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(),但我想知道是否有更好的方法可以通过单击按钮来获取呈现视图控制器?

【问题讨论】:

  • 什么是“呈现视图控制器的名称”?您想确定在哪个单元格上按下了按钮?

标签: ios swift


【解决方案1】:

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

More about delegation design pattern

Another good read

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    相关资源
    最近更新 更多