这是我的代码,在 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
最佳答案
您正在手动调用 drawRect
,我怀疑这是导致此问题的原因。来自文档:
You should never call this method directly yourself. To invalidate part of your view, and thus cause that portion to be redrawn, call the
setNeedsDisplay
orsetNeedsDisplayInRect:
method instead.
不过,在本例中这看起来没有必要。该 View 已添加为您的 View 的 subview ;它会在您的 View 呈现时自动绘制。
关于objective-c - 为什么每一行代码都给我 "invalid context"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9967252/