9

したがって、これは一種の初歩的な質問ですが、現在フォーカスされているアイテムを検出する非常に簡単な方法がわかりませんindexPath
のような非常に簡単なものを見たいと思って周りを見回しましcollectionView.indexPathOfCurrentlyFocusedItemたが、遠く離れたものは見つかりませんでした。だから私は掘り下げて、で似たようなものを見つけよUIFocusEnvironmentUIFocusUpdateContextとしましたが、目的のプロパティを見つけようとしましたが失敗しました。したがって、私が思いつく唯一の解決策は、表示されているすべてのセルを反復処理し、フォーカスされたプロパティが true に設定されたセルを見つけることです。

現在フォーカスされているアイテムを見つけるためのよりシンプルでエレガントな方法はありますindexPathか? (デリゲート メソッドを介して追跡し、View Controller のプロパティに保存する場合を除く)

4

4 に答える 4

20

これには、次のようにUIScreenプロパティを使用できます。focusedView

if let focusedCell = UIScreen.main.focusedView as? UICollectionViewCell {
    if let indexPath = collectionView.indexPath(for: focusedCell) {
        print("IndexPath is \(indexPath)")
    }
}
于 2015-09-30T11:39:21.933 に答える
9

didUpdateFocusInContectを使用- UICollectionViewDelegate

func collectionView(collectionView: UICollectionView, didUpdateFocusInContext context: UICollectionViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
    if collectionView == self.collectionView {
        print(context.nextFocusedIndexPath)
    }
}

これは、フォーカスされるセルの indexPath を返します。次のことも試してください。

context.previouslyFocusedIndexPath

何をしようとしているかによります。

于 2015-09-28T07:46:39.167 に答える
2

これが私がこれをどのように達成したかですshouldUpdateFocusInContext

解決

override func shouldUpdateFocusInContext(context: UIFocusUpdateContext) -> Bool {

    // The magic is in the next two lines
    let cell: UICollectionViewCell = context.nextFocusedView as! UICollectionViewCell
    let indexPath: NSIndexPath? = self.collectionView.indexPathForCell(cell)

    print(indexPath) 
    // <NSIndexPath: 0xc000000000000016> {length = 2, path = 0 - 0}
    
    return true
}
于 2015-11-09T16:57:24.347 に答える