2013-10-28 33 views
0

我做了一個名爲MiniView的UIView子類。UIView不會出現和drawRect方法從來沒有叫

我嘗試如下其添加到我的viewController:

@interface SomeViewController() 

@property (strong, nonatomic) MiniView *miniView; 

@end 

- (void)viewDidLoad 
     { 
     [super viewDidLoad]; 

     self.miniView = [[MiniView alloc] initWithFrame:CGRectMake(20.f, 20.f, 200.f, 200.f)]; 
     _miniView.backgroundColor = [UIColor blackColor]; 
     [self.view addSubview:_miniView]; 
    } 

的MiniView中類看起來是這樣的:

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

- (void)drawRect:(CGRect)rect 
{ 
    NSLog(@"DRAW RECT"); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    UIColor * redColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0]; 
    CGContextSetFillColorWithColor(context, redColor.CGColor); 
    CGContextFillRect(context, self.bounds); 
} 

但drawRect中不會被調用,除非我明確地把它從內setNeedsLayout方法。它也沒有畫任何東西。我試着在drawRect方法中添加一個UIImageView,這看起來很好。但上面的代碼什麼也沒有產生。

我也得到了錯誤:如果我打印drawRect方法和輸出的「矩形」值的日誌語句

: CGContextSetFillColorWithColor: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

,它在200×200是正確的,所以我不知道爲什麼上下文是0x0。

所以一個問題是,drawRect中不會被調用,而另一個問題是,如果我明確地調用它,什麼也不顯示...

+0

啊,我才意識到我在做什麼錯了 - 我已經重新定義了setNeedsDisplay方法在我的班級MiniView中NSLog的到的東西。所以它表現不正確。我把爲[超級setNeedsDisplay]一個電話,現在,它的工作原理*拍打頭部* – Smikey

回答

0

,一定不要調用drawRect中明確地,試試這個:

- (void)viewDidLoad 
     { 
     [super viewDidLoad]; 

     self.miniView = [[MiniView alloc] initWithFrame:CGRectMake(20.f, 20.f, 200.f, 200.f)]; 
     _miniView.backgroundColor = [UIColor blackColor]; 
     [self.view addSubview:_miniView]; 

     [_miniView setNeedsDisplay]; 
    } 
+1

我在其他地方調用setNeedsDisplay,但上面的評論,我意識到我想重新定義它不MiniView中爲[超級setNeedsDisplay]通話。謝謝你的回答 - 它讓我意識到我做錯了什麼。 – Smikey

+0

@Smikey:您應該將其作爲單獨的答案發布,因爲它與Antonio MG建議的不同。 –

+0

現在已經這樣做了。謝謝! – Smikey

1

你可能需要調用setNeedsDisplay上的自定義UIView子類:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    self.miniView = [[MiniView alloc] initWithFrame:CGRectMake(20.f, 20.f, 200.f, 200.f)]; 
    _miniView.backgroundColor = [UIColor blackColor]; 
    [_miniView setNeedsDisplay]; // Added this 
    [self.view addSubview:_miniView]; 
} 

這基本上是一個督促告訴系統你UIView東東ds被重新繪製。有關更多信息,請參閱the docs

在您的drawRect方法
0

那麼包括此行: -

 [super drawRect:rect]; 
+1

在UIView的直接子類中,這不是必需的。 「此方法的默認實現什麼都不做。」 –

1

張貼作爲一個單獨的答案的要求:

實際的問題是,我已經重新定義在MiniView中類的setNeedsDisplay方法,像所以:

- (void)setNeedsDisplay 
{ 
    NSLog(@"Redrawing info: %@", [_info description]); 
} 

因爲我忽略了撥打電話到[super setNeedsDisplay],drawRect中從來沒有被調用,沒有什麼是d rawing。所以這個固定:

- (void)setNeedsDisplay 
{ 
    [super setNeedsDisplay]; 
    NSLog(@"Redrawing info: %@", [_info description]); 
}