user12985516
user12985516

Reputation: 47

Use of unresolved identifier 'UICollection' in separate UICollection Class

I have this class from where I am going to work on a top menu view.

Here is the code:

import UIKit

class TopHomeMenuBar: UIView {

let collectionView: UICollectionView = {

    let layout = UICollectionViewFlowLayout()
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    return cv
}()

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

    addSubview(collectionView)

    backgroundColor = UIColor.systemGreen
}

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

However, I keep getting the error:

Use of unresolved identifier 'UICollection'

The error is highlighting UICollectionView in this line of code:

    let collectionView: UICollectionView = {

Upvotes: 1

Views: 36

Answers (2)

Denis Kakačka
Denis Kakačka

Reputation: 727

Try this way.

private var collectionLayout = UICollectionViewFlowLayout()

lazy var collectionView: UICollectionView = {
    UICollectionView(frame: .zero, collectionViewLayout: collectionLayout)
}()

And then in layoutSubviews set your flow layout as you want it.

override func layoutSubviews() {
    super.layoutSubviews()

    collectionLayout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    collectionLayout.minimumLineSpacing = 0
    collectionLayout.itemSize = CGSize(width: (frame.width - 20) / 5, height: frame.height - 24)
    collectionLayout.scrollDirection = .horizontal
}

Upvotes: 0

ingconti
ingconti

Reputation: 11646

it does work

created JUST now a simple SinlgerView project in XCODE I Controler I put (only to test.. usually view has its own file..)

//
//  ViewController.swift
//
//  Created by ing.conti on 11/06/2020.
//  Copyright © 2020 ing.conti. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }


}


class TopHomeMenuBar: UIView {

    let collectionView: UICollectionView = {

        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        return cv
    }()

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

        addSubview(collectionView)

        backgroundColor = UIColor.systemGreen
    }

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

Upvotes: 1

Related Questions