2012-04-01 65 views
0

這是我的代碼,在iPad模擬器中運行應用程序時,每行都會給我一個「無效上下文」錯誤。 。之後「self.Frame =幀的每一個表態,給出了錯誤如何解決呢爲什麼每行代碼都會給我「無效的上下文」?

- (void)makeFrame:(CGRect)frame number:(NSInteger) number color:(UIColor *) color { 

    float rd1 = 225.00/255.00; 
    float gr1 = 102.00/255.00; 
    float bl1 = 0.00/255.00; 

    float rd2 = 225.00/255.00; 
    float gr2 = 153.00/255.00; 
    float bl2 = 0.00/255.00; 

    self.frame = frame; 
    self.backgroundColor = [UIColor colorWithRed:rd1 green:gr1 blue:bl1 alpha:1.0]; 
    [[self layer] setBorderColor:[[UIColor blackColor] CGColor]]; 
    [[self layer] setBorderWidth:0.5]; 
    [[self layer] setCornerRadius:10]; 
    self.tag = number; // set each button's tag 
    [self setClipsToBounds: YES]; 

    // do date label 
    date = [[UILabel alloc]initWithFrame:CGRectMake(10, 2, 65, 40)]; 
    date.backgroundColor = [UIColor clearColor]; // x y w h 
    date.textColor = [UIColor colorWithRed:rd2 green:gr2 blue:bl2 alpha:1.0]; 
    date.text = [NSString stringWithFormat:@"%d", number]; 
    date.font = [UIFont boldSystemFontOfSize:40]; 
    // date.alpha = 0.2; 
    [self addSubview:date]; 
} 

而且這是一個講求makeFrame代碼:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    allButtons = [NSMutableArray array]; 
    for(int k = 40, m = 0; m < 6; m++, k+= 42) // this controls the vertical distance between rows 
     for(int i = 0, j=32; i < 7; i++, j+=102) { // this controls the size and horizontal distance 
      calendarButton *cb= [calendarButton buttonWithType:UIButtonTypeCustom]; 
      [cb makeFrame:CGRectMake(j, k, 100, 40) number: allButtons.count+1 color:[UIColor orangeColor]]; 
      //      x y w h 
      [self.view addSubview:cb]; 
      [allButtons addObject:cb]; // put it in the array 
     } 

    calendarButton *cb= [calendarButton buttonWithType:UIButtonTypeCustom]; 
    [cb drawRect:CGRectMake(0,0, 100, 40)]; // 150 

回答

1

你正在手動呼叫drawRect,我懷疑是造成這個問題。從文檔:

你不應該直接調用這個方法。要使部分視圖無效,並因此導致該部分重繪,請調用setNeedsDisplaysetNeedsDisplayInRect:方法。

雖然這在這種情況下看起來不是必需的。視圖已添加爲您視圖的子視圖;它會在您的視圖呈現時自動繪製自己。

+0

非常感謝!就是這樣......呃!我知道這是一個重載......不知道爲什麼我沒有看到它...... – SpokaneDude 2012-04-01 19:16:11

+0

我有一個相關的問題:「drawRect」是否被該類中的每個「繪圖」調用?換句話說,我是否需要爲每個不需要特定覆蓋的圖紙創建一個單獨的類? – SpokaneDude 2012-04-01 19:33:08

+0

我不知道你是什麼意思的「繪圖」。每個'UIView'子類都會調用一次'drawRect'。默認的'drawRect'基本上只是繪製其背景,然後爲其所有子視圖調用'drawRect'。任何你需要做某些事情的視圖(如繪製'CGPath'或其他東西)需要實現'drawRect'。如果你沒有進行定製的核心圖形繪製,你根本不需要實現它,因爲UIKit已經內置了大多數渲染工具(例如,如果你正在繪製圖像,使用'UIImageView'等)。 – 2012-04-01 19:50:35

1

您試圖訪問視圖屬性?在視圖控制器。在你的情況self是UIViewController中(或sublcass),以便將其改爲self.view訪問以查看

例如

self.view.frame = frame; 
+0

我認爲'makeFrame'是'calendarButton'類中的一個方法,而不是視圖控制器。 – 2012-04-01 19:11:02

相關問題