Skip to content

Commit ddf3095

Browse files
committed
Update Focus after 0.5 seconds
1 parent 8c17dee commit ddf3095

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

AutoScrollCollectionViewController/ViewController.swift

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
// Copyright © 2016 toshi0383. All rights reserved.
77
//
88

9+
import Async
910
import UIKit
1011

1112
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@@ -15,14 +16,39 @@ class ViewController: UIViewController, UICollectionViewDelegate, UICollectionVi
1516
collectionView.dataSource = self
1617
}
1718
}
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+
1839
override func viewDidLoad() {
1940
super.viewDidLoad()
2041
}
2142

2243
override func viewDidAppear(_ animated: Bool) {
2344
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}
2652
}
2753

2854
// MARK: Delegate & DataSource
@@ -36,6 +62,9 @@ class ViewController: UIViewController, UICollectionViewDelegate, UICollectionVi
3662
func numberOfSections(in collectionView: UICollectionView) -> Int {
3763
return 1
3864
}
65+
func collectionView(_ collectionView: UICollectionView, didUpdateFocusIn context: UICollectionViewFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
66+
_currentIndex = context.nextFocusedIndexPath?.row ?? 0
67+
}
3968
}
4069

4170
class Cell: UICollectionViewCell {

0 commit comments

Comments
 (0)