teach me how to code teach me how to code - 5 months ago 40
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

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

let topButtonFocusGuide = UIFocusGuide()
topButtonFocusGuide.preferredFocusedView = myButton
self.view.addLayoutGuide(topButtonFocusGuide)

self.view.addConstraint(topButtonFocusGuide.topAnchor.constraintEqualToAnchor(myCollectionView.bottomAnchor))
self.view.addConstraint(topButtonFocusGuide.bottomAnchor.constraintEqualToAnchor(self.view.bottomAnchor))
self.view.addConstraint(topButtonFocusGuide.leadingAnchor.constraintEqualToAnchor(myCollectionView.leadingAnchor))
self.view.addConstraint(topButtonFocusGuide.widthAnchor.constraintEqualToAnchor(myCollectionView.widthAnchor))


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'']>

Answer

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

self.view.addSubView(myCollectionView)

Add this like of code before

self.view.addConstraint(topButtonFocusGuide.topAnchor.constraintEqualToAnchor(myCollectionView.bottomAnchor))

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