@IBDesignable CollectionView leads to Xcode crash

Hi!

I have an @IBDesignable UICollectionView

@IBDesignable
class CollectionView: UICollectionView {

    private let cellId = "CollectionViewCell"

    override func awakeFromNib() {
        super.awakeFromNib()
        setup()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setup()
    }

    private func setup() {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: cellId, bundle: bundle)
        register(nib, forCellWithReuseIdentifier: cellId)

        dataSource = self
        delegate = self
    }
}

extension CollectionView: UICollectionViewDataSource {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 2
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        return dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
    }
}

I've noticed that when the Collection View number of items in the attribute inspector is less than func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) returns, it leads to Xcode crash on storyboard rendering.

For example, this

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }

would lead to the crash. The application in the same time works fine in a simulator.

I think this is somehow related to dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) Is there a way to cope the problem?

Does it crash if you set to 1 instead of 3 ?

No, works fine with 1. Any number of items >= func returns works well.

Is this the real code ?

It cannot compile as CollectionView does not conform to UICollectionViewDelegate.

        delegate = self

yields error.

In addition, in IB, number of items is the number of different item types. Usually, it should be 1.

I found this post, if that may help:

https://stackoverflow.com/questions/53040792/uicollection-view-crashes-when-i-change-the-number-of-items-in-data-source

Update: removing the line

        delegate = self

helps to prevent the Xcode crash and prints Crashed status inside the attribute inspector.

Depending on the number of items the index can vary.

(Items = 3, func returns 4)

@IBDesignable CollectionView leads to Xcode crash
 
 
Q