gpt4 book ai didi

swift : How to instantiate a new view controller with separate delegate

转载 作者:行者123 更新时间:2023-11-30 10:37:48 28 4
gpt4 key购买 nike

所以我有一个关于当我单击 tableviewcell 时实例化新 vc 的问题。由于我已将委托(delegate)和数据源分离到单独的类中,因此我不再从 ViewController 继承。除了从委托(delegate)类创建新 VC 之外,我还有哪些选择?另一个潜在的问题是我的显示数组是在另一个单独的 myDataSource 类中创建的。我如何将其传递给 MyDelegate 类?

class ViewController: UITableViewController {
let aDataSource = MyDataSource()
let aDelegate = MyDelegate()

override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = aDataSource
tableView.delegate = aDelegate
}
}


class MyDelegate: NSObject, UITableViewDelegate {


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// i want to do the following but it doesn't work since i'm not inheriting from viewcontroller i guess.

guard let vc = storyboard?.instantiateViewController(withIdentifier: "detailedShowViewController") as? DetailedShowViewController else {
fatalError("Unable to instantiate view controller.")
}

let item = shows[indexPath.row]
vc.show = item

navigationController?.pushViewController(vc, animated: true)
}
}

最佳答案

您可以创建一个委托(delegate)并让您的 View Controller 继承此委托(delegate)来处理回调:

protocol MyViewControllerDelegate {
func didSelectItemAt(_ indexPath: IndexPath)
}

MyDelegate 类中创建一个新属性,例如 weak var myVCDelegate: MyViewControllerDelegate?

让您的 View Controller 继承它并将其自身分配给来自 MyDelegate 的委托(delegate)(或将其注入(inject)到类中)

// In ViewController

aDelegate.myVCDelegate = self


// In MyDelegate class

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Do some stuff

// Pass the position of the item.
myVCDelegate?.didSelectItemAt(indexPath)
}

因此,当您选择一个单元格时,只需调用该函数将indexPath传递给 View Controller ,然后您就可以通过indexPath从数据源获取该项目。

关于 swift : How to instantiate a new view controller with separate delegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57548211/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com