2013-11-27 50 views
0

我已經採取了UIView子類,但是它的背景顏色是不會改變讓UIView的子類,但背景色顯示黑色

該類我使用這些方法

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:CGRectMake(50, 80, 200, 200)]; 
    if (self) 
     { 
     // Initialization code 
     } 
    return self; 
} 

- (void)drawRect:(CGRect)rect{ 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    [[UIColor darkGrayColor]setFill];  
    CGContextClearRect(context, rect); 
    CGContextSetLineWidth(context, 2.0); 

    CGContextBeginPath(context); 
    CGContextSetStrokeColorWithColor(context, [UIColor orangeColor].CGColor); 
    CGContextMoveToPoint(context, 1, 1); 
    CGContextAddLineToPoint(context, 100, 100); 
    CGContextStrokePath(context); // and draw 
} 

我調用這個類主視圖控制器

Newclass *obj =[[Newsclass alloc]init]; 
obj.backgroundColor =[UIColor redColor]; 
[self.view addsubview :obj]; 

但背景顏色默認顯示黑色。它不改變

如果我實現背景色代碼初始化以比不改變幀方法或

拉伸RECT方法。

,如果我的代碼是

- (id)initWithCoder:(NSCoder*)aDecoder 

比它的方法不叫 請建議我UIView子類的黑色背景顏色如何改變

回答

0

首先,你應該做的UIView文件中的顏色部分。

if (self = [super initWithFrame:CGRectMake(220,60, 100, 300)]) 
{ 
    self.backgroundColor =[UIColor greenColor]; 
} 

怎麼過,你不需要在這種情況下,...做的;)

必定會改變你的背景顏色。但接下來會發生的情況是調用Draw rect方法,因爲繪製rect方法在其上繪製視圖(無論您在該方法中繪製什麼),所以顏色不再可見。

- (void)drawRect:(CGRect)rect 
{ 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor); 

    CGRect rectangle = CGRectMake(0,0,200,300); 

    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor); 

    CGContextFillRect(context, rectangle); 
} 

你只是不能直接設置cgcontext的背景顏色,你必須用顏色填充該上下文。 請確保您用視圖的矩形框替換矩形。它對我來說就像一個魅力。