0

我已经以编程方式实现了这个:

  1. tableView 单元格列表。
  2. 每个 tableViewCell 都包含一个 collectionView 和一个 Button。

在此处输入图像描述

现在发生了什么事:

  1. 焦点引擎在集合视图上
  2. 用户向下滚动
  3. 除非我在焦点集合视图的最后一项上,否则焦点引擎会转到下一个集合视图,然后它会转到 VoirTout 按钮。

我想要的是:

  1. 焦点引擎在集合视图上
  2. 用户向下滚动
  3. 焦点引擎转到 Voir Tout 按钮

我已经看到了几个使用preferredFocusEnvironments这样的答案:

 // Trying to force focus on button
    var voirToutButton:  CustomButton? = CustomButton(color: .red, titleString: "");
    override var preferredFocusEnvironments : [UIFocusEnvironment] {
        return [voirToutButton!]
    }

然后在 viewDidLoad 中调用这些:

 // TRYING TO FORCE FOCUS ON VOIR TOUT BUTTON
setNeedsFocusUpdate()
updateFocusIfNeeded()

但是,就我而言,这没有效果。

4

1 回答 1

0

我是这样解决的。我不确定这是最理想的方式,但它确实有效:

class TableViewCell: UITableViewCell {

    var voirToutButton:  CustomButton? = CustomButton(color: .red, titleString: "");
    var shouldRefocusToVoirToutButton:Bool = false
    override var preferredFocusEnvironments : [UIFocusEnvironment] {
            return [voirToutButton!]
    }
    override func shouldUpdateFocus(in context: UIFocusUpdateContext) -> Bool {
        if (self.shouldRefocusToVoirToutButton){
            // Resetting this to false in order to avoid the focus getting stuck on voirToutButton
            self.shouldRefocusToVoirToutButton = false
                    self.setNeedsFocusUpdate()
                   self.updateFocusIfNeeded()
        }
        return true
        
    }
}

extension TableViewCell: UICollectionViewDelegate, UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, shouldUpdateFocusIn context: UICollectionViewFocusUpdateContext) -> Bool {
       
        if let previouslyFocusedItemParent =  context.previouslyFocusedItem?.parentFocusEnvironment as? UICollectionView, let nextFocusedItemParent = context.nextFocusedItem?.parentFocusEnvironment as? UICollectionView  {
          
 let isPreviousFocusInCurrentCollectionView = previouslyFocusedItemParent == self.moviesCollectionView
        let isNextFocusInCurrentCollectionView = nextFocusedItemParent == self.moviesCollectionView
        let isFocusLeavingCollectionView = !(isPreviousFocusInCurrentCollectionView == isNextFocusInCurrentCollectionView)
        let isFocusMovingDown:Bool =  !(context.focusHeading == .up)
        if (isFocusLeavingCollectionView && isFocusMovingDown) {
            self.shouldRefocusToVoirToutButton = true
        }
        return true
        }
            // I remove this else it says that I need to return a bool (!(
        else {
            print("If I remove this else it says that I need to return a bool (!(")
            return true
        }
    }
    
}
于 2020-11-17T15:22:42.877 回答