I cannot get the coordinates of visible rectangle in scroll view after şt scrolls. So when I want to add a subview in a visible rect, I cannot. How can I do that?
-
1Why can't you? The visible rect has an origin of scrollview.contentOffset size of scrollview.bounds.size – Matt Sep 26 '13 at 15:25
4 Answers
CGRect visibleRect = CGRectMake(myScrollView.contentOffset.x, myScrollView.contentOffset.y, myScrollView.contentOffset.x + myScrollView.bounds.size.width, myScrollView.contentOffset.y + myScrollView.bounds.size.height)
This should get you the rect
that is currently visible, after scrolling.
Not what you must decide is, when you want to calculate the rect. If you want to get this on the fly, then do it in thescrollViewDidScroll
method. If you want to get it when user begins scrolling, then do it in scrollViewWillBeginDragging
. If you want it after the user is done scrolling and the scrollView
comes to rest, do it in scrollViewDidEndDragging
and scrollViewDidEndDecelerating
.

- 4,261
- 3
- 32
- 60
-
1The size is incorrect in your answer. You don't add the offset to the size. – Joel Sep 20 '15 at 23:57
The visible rect of a scrollView at all time is as below:
CGRectMake(scrollview.contentOffset.x, scrollview.contentOffset.y, scrollview.frame.size.width, scrollview.frame.size.height)

- 1,181
- 6
- 8
-
1Note, this is correct, but can be simplified to `scrollview.bounds`. For `UIScrollView` the origin of the bounds is the content offset. Also, this is only correct for zoomScale = 1. If zoomed, you must transform the rect to get the correct result. – Joel Sep 21 '15 at 00:12
The visible rect for a UIScrollView
is myScrollView.bounds
. There is no need to use CGRectMake
or use the contentOffset
property, as the other answers suggest (although it does get you to the same place). However, if the scroll view allows zooming, then you need to transform the rect to account for zooming. A number of solutions for applying the transform are provided in this answer.
I'm not entirely sure about what you are asking, but if you need to get the content offset as it is being scrolled, you can just use the delegate method:
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
which will be invoked every time the contentOffset changes.
Alternatively you could use
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
to know the contentOffset
of the scrollview the seconds it stops decelerating.
Or
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
to know the contentOffset
of the scrollview when the user stops panning it around.

- 5,446
- 2
- 23
- 27