teach me how to code teach me how to code - 8 months ago 57
Swift Question

UICollectionViewCell to UIButton Focus

My problem is similar to the problem described in UICollectionViewCell to UIButton Focus in tvOS
but my button is below the

. I tried adding focus guide but I must have done something wrong.

let topButtonFocusGuide = UIFocusGuide()
topButtonFocusGuide.preferredFocusedView = myButton


I get this error:

libc++abi.dylib: terminating with uncaught exception of type NSException
CostomLayout[18448:888102] The view hierarchy is not prepared for the
constraint: <NSLayoutConstraint:0x7fb9e3c5e060 V:[UICollectionView:0x7fb9e501ac00]-(0)-[UIFocusGuide:0x7fb9e3c5b8b0'']>


It looks like you don't have CollectionView in view hierarchy, means you have not added collectionView as subView of view. Please make sure you are adding collectionView as subview before applying any constraints. You can do this like below


Add this like of code before


Update: The new error is because you are not registering cell with UICollectionView, after creating collection view object add this line.

[myCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];

I think you need to read more about collection view, here is a great tutorial to get started with UICollectionView

Apple docs on this topic