I have a UIScrollView
with pagingEnabled
. Added 5 UIStackView
to subview of UIScrollView
and also had one UISegmentedControl
. I want to show currently selected segment and also want to disable horizontal scrolling but the view will able to scroll vertically.
let take an example:
UISegmentedControl
How can I achieve this functionality using UIScrollView
Tried logic:
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
CGFloat xOff = self.scrollView.frame.size.width * self.currentPage;
[self.scrollView setContentSize:CGSizeMake(xOff, self.scrollView.contentSize.height)];
//[self.scrollView setContentOffset:CGPointMake(xOff, 0) animated:true];
}
but using this UIScrollView after changing page When I scroll again go to 0 page.
You can use UICollectionView with paging enabled and inside you can implement UIScrollView with vertical scroll enable. Disable the UICollectionView scroll and change the index collection cell on click using below code:
accepted New, Edited Answer:
Add this in viewDidLayoutSubviews
SWIFT
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let indexPath = IndexPath(item: 12, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: [ .centeredHorizontally], animated: true)
}
Normally, .centerVertically is the case
Objective-C
-(void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:12 inSection:0];
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}