我正在尝试保存一个CGRect数组以与CGContextFillRects一起使用,但我分配给我的minorPlotLines数组的CGRect变量似乎没有得到保存。当对象在这里绘制自己时,minorPlotLines是空的!有谁知道发生了什么?
@interface GraphLineView () {
int numberOfLines;
CGRect *minorPlotLines;
}
@end
@implementation GraphLineView
- (instancetype) initWithFrame: (CGRect) frame {
self = [super initWithFrame:frame];
if (self) {
// Init code
[self setupView];
}
return self;
}
- (instancetype) initWithCoder: (NSCoder *) aDecoder {
if(self == [super initWithCoder:aDecoder]){
[self setupView];
}
return self;
}
- (void) dealloc {
free(minorPlotLines);
}
- (void) setupView {
numberOfLines = 40;
minorPlotLines = malloc(sizeof(struct CGRect)*40);
for(int x = 0; x < numberOfLines; x += 2){
//minorPlotLines[x] = *(CGRect*)malloc(sizeof(CGRect));
minorPlotLines[x] = CGRectMake(x*(self.frame.size.width/numberOfLines), 0, 2, self.frame.size.height);
// minorPlotLines[x+1] = *(CGRect*)malloc(sizeof(CGRect));
minorPlotLines[x+1] = CGRectMake(0, x*(self.frame.size.height/numberOfLines), self.frame.size.width, 2);
}
[self setNeedsDisplay];
}
- (void) drawRect:(CGRect)rect {
// Drawing code
[super drawRect:rect];
for(int x = 0; x < numberOfLines; x += 2){
NSLog(@"R %d = %f", x, minorPlotLines[x].origin.x);
NSLog(@"R %d = %f", x+1, minorPlotLines[x+1].origin.y);
}
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [[UIColor yellowColor] CGColor]);
CGContextFillRects(context, minorPlotLines, numberOfLines);
}
答案 0 :(得分:1)
我尝试将你的代码(构建minorPlotLines
的内容并稍后将内容读回来)拉到另一个项目中,它似乎确实保留了内容,所以你的基本代码本身似乎是合理的。
我会检查以确保在构建数组minorPlotLines
时(即在-setupView
中)实际上有一个非零帧。在你的类只是部分构造的时候调用早期的UI类加载回调是很常见的(例如UIViewController类'回调-viewDidLoad
),你别无选择,只能将某些决定推迟到装货过程。布局尤其在游戏中相对较晚发生,并且因为-setupView
方法在-init
方法中被调用,所以我猜测框架还没有为你的类提供任何布局,因此它没有可用的框架(即你的框架实际上等同于CGRectZero
)。