【问题标题】:Custom delegate to use pushViewController from UIView class自定义委托以使用 UIView 类中的 pushViewController
【发布时间】:2020-06-11 11:46:56
【问题描述】:

我正在尝试从 UIView 类 pushViewController,因此使用自定义委托来使用 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 ?错误说你不能在不传递所需参数的情况下初始化它
  • 是UIView的一个类
  • 请添加HomeCategCollectionView的代码,以便我们看到它的初始化程序
  • 错误的意思是,你必须使用指定的初始化器之一,要么init(categViewModel:要么init?(coder

标签: ios swift xcode delegates


【解决方案1】:

您需要使用所有必需的参数初始化您的HomeCategCollectionView,因此在本例中为categViewModelcoder。以下将起作用。

let viewHomeCategories = HomeCategCollectionView(categViewModel: nil)

当然,理想情况下,您不传递nil,而是传递应该使用的视图模型实例。

【讨论】:

    【解决方案2】:

    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 2011-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多