Search code examples
objective-cswiftuiscrollviewuisegmentedcontroluistackview

How can I disable horizontal scrolling and page will change on click in paging using UIScrollView?


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:

  • Let selected page index = 0
  • User not able to scroll or drag horizontally to navigate to next page.
  • The user can scroll vertically
  • Now User selected page index = 1 in UISegmentedControl
  • 2nd page will be visible
  • Now user not able to scroll or drag to 0 and 2 index

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.


Solution

  • 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];
    }