【发布时间】:2021-05-16 19:40:26
【问题描述】:
尝试将在 collectionView 中选择的值传递到新的 View Controller 以确定要解码的本地 json 文件。得到错误“不能在属性初始化器中使用实例成员'selectedCategory';属性初始化器在'self'可用之前运行”
初始 VC:
extension MenuViewController: UICollectionViewDataSource {
...
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectedVC = storyboard?.instantiateViewController(withIdentifier: "SelectImageViewController") as! SelectImageViewController
selectedVC.selectedCategory = categories[indexPath.row].category
navigationController?.pushViewController(selectedVC, animated: true)
}
}
第二个VC:
class SelectImageViewController: UIViewController {
lazy var selectedCategory: String = ""
var selectedArray = Bundle.main.decode([Images].self, from: "\(selectedCategory).json")
override func viewDidLoad() {
super.viewDidLoad()
...
}
我尝试了其他帖子中建议的惰性 var 和 init 方法,但没有成功。
【问题讨论】:
-
“但没有运气”是什么意思?你到底是如何尝试的?你遇到了什么错误?
-
我得到了相同的“初始化程序在 'self' 可用之前运行惰性变量错误。我承认我对 init 不太熟悉 - 尝试在 init() { } 中单独添加我的属性和得到了 'required' 初始化程序 'init(coder:)' 必须由 'UIViewController' 的子类提供。
-
你到底做了什么偷懒?你应该让
selectedArray变得懒惰,而不是selectedCategory。
标签: ios json swift collectionview