Strange behavior with partially transparent content inside a UIScrollView


The implementation of my view is below. scrollView is an iVar of type UIScrollView.

The "strange behavior" is that as I scroll the view, the background gradually changes from orange to green. It seems like the almost-transparent label background is somehow stacking on itself until you end up with a green background. But I don't understand why it would do that. Can anyone explain?

#import "ViewWithScrollView.h"

@implementation ViewWithScrollView

@synthesize scrollView;

-(void) layoutSubviews {
    scrollView.frame = self.bounds;
    CGSize size = self.frame.size;
    scrollView.contentSize = size;
    scrollView.backgroundColor = [UIColor orangeColor];
//  scrollView.clearsContextBeforeDrawing = YES;    //These two lines can be commented in or out; it makes no difference.
//  scrollView.opaque = NO;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0,0,size.width, size.height)];
    label.textAlignment = UITextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:200];
    label.text = @"Princess!";
    label.textColor = [UIColor blackColor];
    label.backgroundColor = [UIColor colorWithRed:0. green:1. blue:0. alpha:0.01];
//  label.opaque = NO;  // same for these two lines
//  label.clearsContextBeforeDrawing = YES;

    [scrollView addSubview: label];

- (id)initWithFrame: (CGRect) frame {
    self = [super initWithFrame:frame];
    if (self) {
//      self.opaque = NO;  //again, commenting these in or out makes no difference
//      self.clearsContextBeforeDrawing = YES;
        scrollView = [[UIScrollView alloc]init];
        [self addSubview:scrollView];
    return self;

Every time -layoutSubviews is called, you're creating a new label. This is probably happening more often than you think, and they're piling up.

If you're always going to have a label in your view, go ahead and make it an instance variable. Move the creation of the label to your view's -initWithFrame: method, alongside your scrollview. Add it as a subview there, too.

Basically, put the stuff you want to do once (object creation, hierarchy) in -initWithFrame:, and the stuff you might need to do repeatedly because of layout changes (sizing, positioning, etc) into -layoutSubviews.