How to set background color to the content area in UIScrollView?

CKT picture CKT · Dec 4, 2012 · Viewed 9.5k times · Source

I am using an UIScrollView in my application, my requirement is I have to add background color to the UIScrollView but when user drags at the extreme top or at the extreme bottom the area other than the content/out side the content which shows in the scroll view should be shown with different color just like in UIWebView. In web view if we drag down at the top or drap up at the bottom it will show default background image/gray color and the web view content background color is diff(default white).Can anyone help me in achieving this.

thank you.

Answer

Matt Garrod picture Matt Garrod · Dec 4, 2012

The trick is to add subviews to the ScrollView that sit above and below the content. This way, they only appear when the content is dragged up or down.

UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, -200, scroll.bounds.size.width, 200)];
[topView setBackgroundColor:[UIColor darkGrayColor]];
[scroll addSubview:topView];
[topView release];

UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, scroll.bounds.size.height, scroll.bounds.size.width, 200)];
[bottomView setBackgroundColor:[UIColor darkGrayColor]];
[scroll addSubview:bottomView];
[bottomView release];