这是我的代码,其中每行都在iPad模拟器中运行应用程序时给出了“无效上下文”错误。 “self.Frame = 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
答案 0 :(得分:1)
您正尝试访问视图控制器中的视图属性。在您的情况下,self
是UIViewController(或sublcass),将其更改为self.view
以访问视图
E.g。
self.view.frame = frame;
答案 1 :(得分:1)
您手动调用drawRect
,我怀疑这是导致此问题。来自文档:
您不应该直接自己调用此方法。要使部分视图无效,从而导致重新绘制该部分,请改为调用
setNeedsDisplay
或setNeedsDisplayInRect:
方法。
但在这种情况下,这看起来并不必要。该视图已添加为您视图的子视图;它会在你的视图呈现时自动绘制。