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?
Asked
Active
Viewed 6.6k times
6 Answers
91
Use the following code:
scrollView.contentOffset = CGPoint(x: 0, y: 0)

Rashid Latif
- 2,809
- 22
- 26

Saurabh Passolia
- 8,099
- 1
- 26
- 41
-
1scrollView.contentOffset = CGPointMake(0, 0); – user1072740 Dec 27 '11 at 13:02
-
28Use [scrollView setContentOffset:CGPointMake(0, 0) animated:YES] if you want animation. – acoustic Oct 20 '13 at 12:39
48
To animate your scrolling do this:
CGRect frame = CGRectMake(0, 768, 1024, 748); //wherever you want to scroll
[self.scrollView scrollRectToVisible:frame animated:YES];

inorganik
- 24,255
- 17
- 90
- 114
-
Is there a way where you wouldn't have to specify width and height of the scroll view? – xtrinch May 14 '16 at 13:59
4
Easiest way with animation ->
[scrollView setContentOffset:CGPointMake(0, 0) animated:YES]

Kakshil Shah
- 3,466
- 1
- 17
- 31
1
The swift 3 version of the answer is:
scrollView.contentOffset = CGPoint(x: 0.0, y: 0.0)

Arjun Nagineni
- 11
- 2
0
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

Irsyad Ashari
- 17
- 6
0
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
scrollView.setContentOffset(CGPoint(x: 0.0, y: 350.0), animated: true)
}

Threadripper
- 622
- 10
- 15