我最近开始使用 swift 进行依赖注入,但我不知道如何在连接到另一个 Viewcontroller 时传递自定义类。
class Content {
var title:String
var about:String
var location:String
init(data: [String: Any]) {
self.title = data["title"] as? String ?? ""
self.about = data["about"] as? String ?? ""
self.location = data["location"] as? String ?? ""
}
}
第一个视图控制器 - 执行 segue 并传递必要的数据。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: "NextView", sender: self.allcontent[indexPath.item])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "NextView" {
let vc = segue.destination as! NextViewController
let selectedRow = sender as? Content
vc.content = selectedRow!
}
}
尝试使用第一个 ViewController 传递的自定义类来启动 NextViewcontroller。
class NextViewController: UIViewController {
var content: Content
init(content: Content) {
self.content = content
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// this way i can access properties from the custom class directly
//content.title
//content.about
}
我不断收到不同的警告,因为我不确定如何正确构建它。
我已经在示例中看到了下面的代码,但我不明白“编码器”是什么或者它应该如何使用。
class EditUserViewController: UIViewController {
var selectedUser: User
init?(coder: NSCoder, selectedUser: User) {
self.selectedUser = selectedUser
super.init(coder: coder)
}
required init?(coder: NSCoder) {
fatalError("You must create this view controller with a user.")
}
// ...
}
任何帮助或示例将不胜感激。
例如,如果您不想使用 NSCoder 并且没有指定您不使用 nib 文件或捆绑包来初始化视图控制器。你可以像这样初始化
class NextViewController: UIViewController {
var content: Content
init(content: Content) {
self.content = content
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// this way i can access properties from the custom class directly
//content.title
//content.about
}