Search code examples
iosswiftuiscrollviewscroll-paging

How to start horizontal scroll view from end page in SWIFT


I have a horizontal scroll view and I have enabled paging option. So I have added total 3 image views in 3 pages "horizontally". I want my last page to display first. i.e. start from end right. Here is my code:

self.myScrollView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)

    let scrollViewWidth = self.myScrollView.frame.width
    let scrollViewHeight = self.myScrollView.frame.height

    let imgOne = UIImageView(frame: CGRectMake(0, 0, scrollViewWidth, scrollViewHeight))
    let imgTwo = UIImageView(frame: CGRectMake(-(scrollViewWidth), 0, scrollViewWidth, scrollViewHeight))
    let imgThree = UIImageView(frame: CGRectMake(-(scrollViewWidth)*2, 0, scrollViewWidth, scrollViewHeight))

    imgOne.image = UIImage(named: "0")
    imgTwo.image = UIImage(named: "1")
    imgThree.image = UIImage(named: "2")

    self.myScrollView.addSubview(imgOne)
    self.myScrollView.addSubview(imgTwo)
    self.myScrollView.addSubview(imgThree)

    self.myScrollView.contentSize = CGSizeMake(scrollViewWidth*3, 0)

Solution

  • Initially set contentOffset to scrollViewWidth*2 which will scroll horizontally to two pages:

    scrollView.contentOffset = CGPointMake(scrollViewWidth*2,0)
    

    and you can set to whatever value you want in X value to scroll horizontally.