ios - Swift - 来自 TableView 的协议(protocol)委托(delegate)不起作用 - 模态呈现

标签 ios swift uitableview delegates presentmodalviewcontroller

我有一个带有按钮的 View Controller ,单击该按钮会转到带有 TableView 的第二个 View Controller 。这两个场景通过 Storyboard联系起来,作为 Present Modally。当在第二个 View Controller 的 TableView 中选择一行时,我希望第一个 View Controller 中的按钮文本发生变化。

选择单元格时按钮没有改变的原因是什么?

非常感谢任何帮助,我仍然是 Swift 的初学者。

下面是相关的代码行:

View Controller 1

class ChartsViewController: UIViewController {

    @IBOutlet weak var titleButton: UIButton!

}

extension ChartsViewController: ModalDelegate {

    func didSelectValue(value: String) {
        self.titleButton.setTitle(value, for: .normal)
        }
}

View Controller 2

protocol ModalDelegate: class {
    func didSelectValue(value: String)
}

class DashboardModalViewController: UIViewController {
    var delegate: ModalDelegate?
}

extension DashboardModalViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let rowTitle = self.rows[indexPath.row].text
        print (rowTitle)
        delegate?.didSelectValue(value: rowTitle)
        dismiss(animated: true, completion: nil)

    }
}

最佳答案

我认为您需要在 View Controller 1 的 prepare 方法中设置第二个 Controller 的委托(delegate),例如:

// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let dashboardModalViewController = segue.destination as? DashboardModalViewController {
        dashboardModalViewController.delegate = self
    }
}

关于ios - Swift - 来自 TableView 的协议(protocol)委托(delegate)不起作用 - 模态呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48057640/

相关文章:

objective-c - ViewDidAppear iOS 4.3 vs iOS 5,加载屏幕不会出现在 4.3

ios - 使用 Core Data 在表格 View 中编辑行位置

ios - 使用本地化的 Storyboard 进行即时本地化

ios - Swift:在 ViewController 中显示名称

swift - 如何断言结构符合协议(protocol)?

iPhone:如何在drawRect中换行文本?

android - 打开特定应用的权限设置 flutter ?

c# - Xamarin.窗体 : How to use localization independent of device language

ios - removeFromSuperview() 不工作

ios - Swift 如何创建从根 VC 到嵌入式 VC 的协议(protocol)委托(delegate)