iosswiftuicollectionviewdelegate

Cannot assign value of type NSObject -() Classname to type uicollectionviewdelegate


I am using view and implementing a collectionview into it

When I am trying to refer datasource and delegate to my colelctionview it give error

my ClassFile

class MenuBar : UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout{

let collectionView : UICollectionView = {

    let layout = UICollectionViewFlowLayout()
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    cv.backgroundColor = UIColor.rgb(red: 230, green: 32, blue: 31)
    cv.delegate = self  // Error here

    return cv

}()

override init(frame: CGRect){
    super.init(frame: frame)

}


required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

}

I can not give the delegate and datasource to my collectionview I have implemented the following two methods also

cellForItemAt indexPath numberOfItemsInSection

Any help will be appriciated


Solution

  • It is because you trying to access self in closure

    lazy var collectionView : UICollectionView = {
        [unowned self] in
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = UIColor.rgb(red: 230, green: 32, blue: 31)
        cv.delegate = self  // Error here
    
        return cv
    
    }()
    

    this should work