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

Commit

Permalink
When selecting segment the control scrolls to it only if required to …
Browse files Browse the repository at this point in the history
…bring it in visible area.
  • Loading branch information
Goce Petrovski committed Apr 23, 2019
1 parent 3ce6943 commit f545db1
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions ScrollableSegmentedControl/ScrollableSegmentedControl.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public enum ScrollableSegmentedControlSegmentStyle: Int {

if indexPath != nil {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05, execute: {
self.collectionView?.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionView.ScrollPosition.left)
self.collectionView?.selectItem(at: indexPath, animated: true, scrollPosition: .left)
})
}
}
Expand Down Expand Up @@ -265,8 +265,18 @@ public enum ScrollableSegmentedControlSegmentStyle: Int {
}

if selectedSegmentIndex >= 0 {
var scrollPossition:UICollectionView.ScrollPosition = .bottom
let indexPath = IndexPath(item: selectedSegmentIndex, section: 0)
collectionView?.selectItem(at: indexPath, animated: true, scrollPosition: .left)
if let atribs = collectionView?.layoutAttributesForItem(at: indexPath) {
let frame = atribs.frame
if frame.origin.x < collectionView!.contentOffset.x {
scrollPossition = .left
} else if frame.origin.x + frame.size.width > (collectionView!.frame.size.width + collectionView!.contentOffset.x) {
scrollPossition = .right
}
}

collectionView?.selectItem(at: indexPath, animated: true, scrollPosition: scrollPossition)
} else {
if let indexPath = collectionView?.indexPathsForSelectedItems?.first {
collectionView?.deselectItem(at: indexPath, animated: true)
Expand Down Expand Up @@ -387,7 +397,7 @@ public enum ScrollableSegmentedControlSegmentStyle: Int {
collectionView_.reloadData()
if selectedSegmentIndex >= 0 {
let indexPath = IndexPath(item: selectedSegmentIndex, section: 0)
collectionView_.selectItem(at: indexPath, animated: true, scrollPosition: .left)
collectionView_.selectItem(at: indexPath, animated: true, scrollPosition: .bottom)
}
}
}
Expand Down

0 comments on commit f545db1

Please sign in to comment.