Search code examples
uicollectionviewtvosapple-tv

UIFocusGuide doesn't work on UICollectionView in tvOS


Basing on this post: UICollectionViewCell to UIButton Focus in tvOS, I'm adding a UIFocusGuide so when the user are on the right of the collectionview, can select the button on left-buttom.

Using this code:

focusGuide = UIFocusGuide();
focusGuide.preferredFocusedView = btClick
view.addLayoutGuide(focusGuide)
focusGuide.topAnchor.constraintEqualToAnchor(collectionView.topAnchor).active = true
focusGuide.bottomAnchor.constraintEqualToAnchor(btClick.bottomAnchor).active = true
focusGuide.leadingAnchor.constraintEqualToAnchor(collectionView.leadingAnchor).active = true
focusGuide.widthAnchor.constraintEqualToAnchor(collectionView.widthAnchor).active = true

In my example I added a usefull code created by Jack Cox that shows the 'invisible' layout guides, and everything seems good because the layout begin on the top of the collectionView and ends on the bottom of the button.

But it doesn't works, the button only can be selected if the user are on the left of collectionView, on this image you can only going to button from item 1 and item 6.

enter image description here

I've made a little example on github here, I don't know what I'm doing wrong.


Solution

  • I have already figured out, the mistake was to create the focus with the entire size of the collectionView now I've created a focus guide just below the collectionView and set preferredFocusedViewto the button.

    Using this code:

    focusGuide = UIFocusGuide();
    focusGuide.preferredFocusedView = btClick
    view.addLayoutGuide(focusGuide)
    
    //Modified the size of the UIFocusGuide
    focusGuide.topAnchor.constraintEqualToAnchor(btClick.topAnchor).active = true   
    focusGuide.rightAnchor.constraintEqualToAnchor(collectionView.rightAnchor).active = true
        
    focusGuide.widthAnchor.constraintEqualToAnchor(btClick.widthAnchor, multiplier: 8).active = true
    focusGuide.heightAnchor.constraintEqualToAnchor(btClick.heightAnchor).active = true
    

    Now the guide look like this: enter image description here

    I've just committ the changes to github maybe it helps anyone else.