Question

I have an app with several SKScenes. To keep it snappy, I have a single UIViewController, that handles 1 SKView.

I'm trying to add a UICollectionView to one of the SKScenes. However the problem comes when I try to set the delegate for the collection view to the SKScene initialising it.

I initialise it here:

- (id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size]) {

        //Initialise collectionView
        UICollectionViewLayout *layout = [[UICollectionViewLayout alloc] init];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView setBackgroundColor:[UIColor redColor]];
    }
    return self;
}

After initialising, I add the collection view as a subview of the UIViewController's view by calling:

- (void)didMoveToView:(SKView *)view
{
    [self.view addSubview:_collectionView];
}

But the delegate or datasource methods aren't called. I've set up the header:

@interface BrowseScene : SKScene <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

I'm guessing that despite setting self as the delegate, once the collection view is added, it is added as a subview of the UIViewController's SKView, and therefore has no reference to the SKScene that initialised it. I tried calling:

_collectionView.delegate = self.view.scene;

But I get a compiler error saying SKScene is an incompatible type for UICollectionViewDelegate.

So my question is, how best to approach this?

Was it helpful?

Solution

It turns out, the problem lay in how I was initialising the UICollectionView, not where. And it's perfectly ok to set an SKScene as the delegate class.

The main reason the delegates weren't being called was because I'd initialised the collectionView with an empty layout object (as UICollectionViewLayout is just an abstract class). I initialised with a standard UICollectionViewFlowLayout instead, and the methods were then called when the class initialised.

I was also missing a call to

[_collectionView registerClass:[collectionViewCell class] forCellWithReuseIdentifier:@"collectionViewCell"];

(In the complete code, I had calls to reloadData, so that wasn't the problem here).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top