2012-07-30 63 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