我有一个带有按钮的 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/