2012-07-30 61 views
0

我想創建一個UIView Class,您可以使用幾個選項進行初始化。UIView帶選項的drawRect方法

我認爲問題是drawRect()方法。是否有可能有一定的選項來初始化類像

[[MyUIView alloc]initWithColor:[UIColor blueColor]] 

我讀,我不應該叫drawRect()方法,無需初始化的對象。

那麼,如何才能實現上面的聲明,而無需手動調用它?

我迄今爲止嘗試:

我想,我可能只是初始化視圖,然後調用方法

[MyView changeColorTo:green] 

它試圖重新繪製視圖,但是我不能得到那個工作。

也許重要的是我在drawRect()方法中用coreGraphics(具有某種顏色,應該可選)繪製圓角矩形。

我該如何實現自己想要的行爲?

回答

1

呼叫

[self setNeedsDisplayInRect:aCGRect]; 

調用的drawRect:爲您服務。

編輯上的color屬性:

@interface MyView: UIView 

@property (nonatomic, strong) UIColor *drawColor; 

@end 

@implementation MyView 

@synthesize drawColor; 

- (id)initWithWhatever 
{ 
    self.drawColor = [UIColor infraRedColor]; 
    [self setNeedsDisplayInRect:aRect]; 
} 

- (void)drawRect:(CGRect)r 
{ 
    // use self.drawColor 
} 

@end 
+0

如果我不喜歡這樣,將繪製默認的矩形。我怎樣才能爲該呼叫添加一個選項。 – arnoapp 2012-07-30 21:26:38

+0

@ AzzUrr1請參閱更新。 – 2012-07-30 21:27:46

+0

嗯也許它是一個愚蠢的問題,但我怎麼能添加一個像顏色選項,如果我用CGRect setNeedsDisplay? – arnoapp 2012-07-30 21:32:19