2011-01-14 56 views
0

我的視圖的實現如下。 scrollView是一個類型爲UIScrollView的iVar。UIScrollView中部分透明內容的奇怪行爲

「奇怪的行爲」是當我滾動視圖時,背景從橙色逐漸變爲綠色。看起來,幾乎透明的標籤背景在某種程度上疊加在自身上,直到最終呈現綠色背景。但我不明白爲什麼它會這樣做。誰能解釋一下?

#import "ViewWithScrollView.h" 

@implementation ViewWithScrollView 

@synthesize scrollView; 

-(void) layoutSubviews { 
    scrollView.frame = self.bounds; 
    CGSize size = self.frame.size; 
    size.width*=2; 
    size.height*=2; 
    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; 
} 
@end 

回答

1

每次調用-layoutSubviews時,都會創建一個新標籤。這可能比你想象的更頻繁,而且它們堆積如山。

如果您總是要在您的視圖中添加一個標籤,請繼續並使其成爲實例變量。將標籤的創建移動到您的視圖的-initWithFrame:方法中,並與您的滾動視圖一起移動。將它作爲子視圖添加到其中。

基本上,把你想做的東西(對象創建,層次結構)放在-initWithFrame:中,以及由於佈局更改(尺寸調整,定位等)到-layoutSubviews而可能需要重複執行的操作。

0

我解決了我的問題;

在我的子視圖類

viewDidLoad中

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view from its nib. 
    self.view.backgroundColor = [UIColor clearColor]; 
    image.backgroundColor = [UIColor clearColor]; 
}