我试图从UIView类中推送ViewController,因此使用了自定义委托来使用pushViewController。以下是错误信息。
Cannot invoke initializer for type 'HomeCategCollectionView' with no arguments
以下是代码。
// ViewController
override func viewDidLoad() {
super.viewDidLoad()
let viewHomeCategories = HomeCategCollectionView() // here error comes
viewHomeCateg.delegate = self
}
// UIView class
private func showCategDetails(indexPath: IndexPath) {
delegate?.pushToListingButton()
}
更新:HomeCategCollectionView
class HomeCategCollectionViewModel {
var categViewVMs: [HomeCategCellViewModel]?
init(categModels: [GVMHomeCateg]?) {
self.categViewVMs = categModels?.map({
HomeCategCellViewModel(categ: $0)
})
}
}
protocol ListingDelegate : class {
func pushToListingButton()
}
class HomeCategCollectionView: UIView {
// MARK: Initialization and view setup
init(categViewModel: HomeCategCollectionViewModel?) {
self.viewModel = categViewModel
super.init(frame: .zero)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
}
请指导。希望我把我的疑问说清楚了,如果不清楚,请随时提问.谢谢。
你的初始化器 HomeCategCollectionView
是 init(categViewModel: HomeCategCollectionViewModel?)
所以你需要调用它的所有参数。
// ViewController
override func viewDidLoad() {
super.viewDidLoad()
let data: [GVMHomeCateg] = // Your data
let viewModel = HomeCategCollectionViewModel(categModels: data)
let viewHomeCategories = HomeCategCollectionView(categViewModel: viewModel)
viewHomeCateg.delegate = self
}
或者
override func viewDidLoad() {
super.viewDidLoad()
let viewHomeCategories = HomeCategCollectionView(categViewModel: nil)
viewHomeCateg.delegate = self
}
您需要初始化您的 HomeCategCollectionView
含有所有必要的参数,所以在本例中 categViewModel
或 coder
. 下面的就可以了。
let viewHomeCategories = HomeCategCollectionView(categViewModel: nil)
理想情况下当然是你不通过 nil
但应该使用的视图模型的实例。