6
6
// Copyright © 2016 toshi0383. All rights reserved.
7
7
//
8
8
9
+ import Async
9
10
import UIKit
10
11
11
12
class ViewController : UIViewController , UICollectionViewDelegate , UICollectionViewDataSource {
@@ -15,14 +16,39 @@ class ViewController: UIViewController, UICollectionViewDelegate, UICollectionVi
15
16
collectionView. dataSource = self
16
17
}
17
18
}
19
+ private var focusUpdateTask : Async ?
20
+ private var _currentIndex : Int = 0
21
+ private func updateCurrentIndex( _ index: Int ) {
22
+ _currentIndex = index
23
+ collectionView. scrollToItem ( at: currentIndexPath, at: . centeredVertically, animated: true )
24
+ // This is also okay.
25
+ //let point = CGPoint(x: 0, y: 290 + 540*index)
26
+ //collectionView.setContentOffset(point, animated: true)
27
+ updateFocusWithDelay ( )
28
+ }
29
+ func updateFocusWithDelay( ) {
30
+ focusUpdateTask? . cancel ( )
31
+ focusUpdateTask = Async . main ( after: 0.5 ) {
32
+ self . setNeedsFocusUpdate ( )
33
+ }
34
+ }
35
+ private var currentIndexPath : IndexPath {
36
+ return IndexPath ( item: _currentIndex, section: 0 )
37
+ }
38
+
18
39
override func viewDidLoad( ) {
19
40
super. viewDidLoad ( )
20
41
}
21
42
22
43
override func viewDidAppear( _ animated: Bool ) {
23
44
super. viewDidAppear ( animated)
24
- let indexPath = IndexPath ( item: 5 , section: 0 )
25
- collectionView. scrollToItem ( at: indexPath, at: . centeredVertically, animated: true )
45
+ updateCurrentIndex ( 5 )
46
+ }
47
+
48
+ // MARK: UIFocusEnvironment
49
+ override var preferredFocusEnvironments : [ UIFocusEnvironment ] {
50
+ let cell = collectionView? . cellForItem ( at: currentIndexPath)
51
+ return [ cell ] . flatMap { $0}
26
52
}
27
53
28
54
// MARK: Delegate & DataSource
@@ -36,6 +62,9 @@ class ViewController: UIViewController, UICollectionViewDelegate, UICollectionVi
36
62
func numberOfSections( in collectionView: UICollectionView ) -> Int {
37
63
return 1
38
64
}
65
+ func collectionView( _ collectionView: UICollectionView , didUpdateFocusIn context: UICollectionViewFocusUpdateContext , with coordinator: UIFocusAnimationCoordinator ) {
66
+ _currentIndex = context. nextFocusedIndexPath? . row ?? 0
67
+ }
39
68
}
40
69
41
70
class Cell : UICollectionViewCell {
0 commit comments