Skip to content
This repository was archived by the owner on Apr 11, 2021. It is now read-only.

Commit f545db1

Browse files
author
Goce Petrovski
committed
When selecting segment the control scrolls to it only if required to bring it in visible area.
1 parent 3ce6943 commit f545db1

1 file changed

Lines changed: 13 additions & 3 deletions

File tree

ScrollableSegmentedControl/ScrollableSegmentedControl.swift

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ public enum ScrollableSegmentedControlSegmentStyle: Int {
7474

7575
if indexPath != nil {
7676
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05, execute: {
77-
self.collectionView?.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionView.ScrollPosition.left)
77+
self.collectionView?.selectItem(at: indexPath, animated: true, scrollPosition: .left)
7878
})
7979
}
8080
}
@@ -265,8 +265,18 @@ public enum ScrollableSegmentedControlSegmentStyle: Int {
265265
}
266266

267267
if selectedSegmentIndex >= 0 {
268+
var scrollPossition:UICollectionView.ScrollPosition = .bottom
268269
let indexPath = IndexPath(item: selectedSegmentIndex, section: 0)
269-
collectionView?.selectItem(at: indexPath, animated: true, scrollPosition: .left)
270+
if let atribs = collectionView?.layoutAttributesForItem(at: indexPath) {
271+
let frame = atribs.frame
272+
if frame.origin.x < collectionView!.contentOffset.x {
273+
scrollPossition = .left
274+
} else if frame.origin.x + frame.size.width > (collectionView!.frame.size.width + collectionView!.contentOffset.x) {
275+
scrollPossition = .right
276+
}
277+
}
278+
279+
collectionView?.selectItem(at: indexPath, animated: true, scrollPosition: scrollPossition)
270280
} else {
271281
if let indexPath = collectionView?.indexPathsForSelectedItems?.first {
272282
collectionView?.deselectItem(at: indexPath, animated: true)
@@ -387,7 +397,7 @@ public enum ScrollableSegmentedControlSegmentStyle: Int {
387397
collectionView_.reloadData()
388398
if selectedSegmentIndex >= 0 {
389399
let indexPath = IndexPath(item: selectedSegmentIndex, section: 0)
390-
collectionView_.selectItem(at: indexPath, animated: true, scrollPosition: .left)
400+
collectionView_.selectItem(at: indexPath, animated: true, scrollPosition: .bottom)
391401
}
392402
}
393403
}

0 commit comments

Comments
 (0)