user1072740
user1072740

Reputation: 660

How do I scroll to a position programmatically in UIScrollView

I have a scroll view which scrolls horizontally. I just added images, labels and a webview in it and there are many objects in it. I want to directly scroll to the first object in the scroll view. How do I do this?

Upvotes: 48

Views: 67794

Answers (6)

Threadripper
Threadripper

Reputation: 652

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        scrollView.setContentOffset(CGPoint(x: 0.0, y: 350.0), animated: true)
    }

Upvotes: 0

Saurabh Passolia
Saurabh Passolia

Reputation: 8109

Use the following code:

scrollView.contentOffset = CGPoint(x: 0, y: 0)

Upvotes: 91

Irsyad Ashari
Irsyad Ashari

Reputation: 17

If someone wonder how to do it in Swift 5 with xcode 11:

I put negative value in the x parameters becouse I want to scroll to left

let frame = CGRect(x: -540, y: 0, width: 1080, height: 370); //wherever you want to scroll
boardScrollView.scrollRectToVisible(frame, animated: true) // set animated to true if you want to animate it

Upvotes: 0

Kakshil Shah
Kakshil Shah

Reputation: 3816

Easiest way with animation ->

[scrollView setContentOffset:CGPointMake(0, 0) animated:YES]

Upvotes: 4

Arjun Nagineni
Arjun Nagineni

Reputation: 11

The swift 3 version of the answer is:

scrollView.contentOffset = CGPoint(x: 0.0, y: 0.0)

Upvotes: 1

inorganik
inorganik

Reputation: 25535

To animate your scrolling do this:

CGRect frame = CGRectMake(0, 768, 1024, 748); //wherever you want to scroll 
[self.scrollView scrollRectToVisible:frame animated:YES];

Upvotes: 48

Related Questions