UILabel.layer未被保留在for循环范围之外

时间:2012-09-16 18:57:06

标签: iphone ios core-animation calayer quartz-graphics

我有一个循环制作一些UILabel并将他们的.layers添加到CALayer我在屏幕外渲染到我后来呈现的UIImage的上下文(BTW:我在传回之前在另一个队列上进行渲染主要。)

如果我在循环中这样做:

for (i=0; i<offlineModel.modelArray.count; i++) {

    UILabel *newLabel = [[UILabel alloc] init];
    [newLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:9.0]];
    [newLabel setTextColor:[UIColor colorWithRed:76/255.0 green:76/255.0 blue:78/255.0 alpha:1.0]];
    [newLabel setShadowColor:[UIColor whiteColor]];
    [newLabel setShadowOffset:CGSizeMake(1, 1)];
    [newLabel setBackgroundColor:[UIColor greenColor]];
    [newLabel setTextAlignment:UITextAlignmentCenter];
    [newLabel setNumberOfLines:0];

    [newLabel setText:[(LVBarGraphModelPair *)[offlineModel.modelArray objectAtIndex:i] xValue]];
    [newLabel setBounds:CGRectMake(0, 0, barWidth+barSpacing, 3*8.0)];
    [newLabel setAdjustsFontSizeToFitWidth:NO];
    [newLabel sizeToFit];

    CGPoint center = CGPointMake((((offlineModel.modelArray.count-i-1)*barSpacing)+placeholderBarContainerLayerRect.origin.x+(.5*barWidth)), placeholderBarContainerLayerRect.size.height);

    [newLabel setCenter:center];
    [newLabel setFrame:CGRectMake(lroundf(newLabel.frame.origin.x), lroundf(placeholderBarContainerLayerRect.origin.y + placeholderBarContainerLayerRect.size.height+LVBARGRAPH_BAR_ANIMATION_XAXIS_LABELS_OFFSET_X), newLabel.frame.size.width, newLabel.frame.size.height)];

    [layer addSublayer:newLabel.layer];
}

我得到黑色的标签应该是: Black Rects instead of labels 因此,要解决问题,我只需删除循环(相同代码)即可创建一个而不是6:

    UILabel *newLabel = [[UILabel alloc] init];
    [newLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:9.0]];
    [newLabel setTextColor:[UIColor colorWithRed:76/255.0 green:76/255.0 blue:78/255.0 alpha:1.0]];
    [newLabel setShadowColor:[UIColor whiteColor]];
    [newLabel setShadowOffset:CGSizeMake(1, 1)];
    [newLabel setBackgroundColor:[UIColor greenColor]];
    [newLabel setTextAlignment:UITextAlignmentCenter];
    [newLabel setNumberOfLines:0];

    [newLabel setText:[(LVBarGraphModelPair *)[offlineModel.modelArray objectAtIndex:i] xValue]];
    [newLabel setBounds:CGRectMake(0, 0, barWidth+barSpacing, 3*8.0)];
    [newLabel setAdjustsFontSizeToFitWidth:NO];
    [newLabel sizeToFit];

    CGPoint center = CGPointMake((((offlineModel.modelArray.count-i-1)*barSpacing)+placeholderBarContainerLayerRect.origin.x+(.5*barWidth)), placeholderBarContainerLayerRect.size.height);

    [newLabel setCenter:center];
    [newLabel setFrame:CGRectMake(lroundf(newLabel.frame.origin.x), lroundf(placeholderBarContainerLayerRect.origin.y + placeholderBarContainerLayerRect.size.height+LVBARGRAPH_BAR_ANIMATION_XAXIS_LABELS_OFFSET_X), newLabel.frame.size.width, newLabel.frame.size.height)];

    [layer addSublayer:newLabel.layer];

Without loop it shows up!

就是这样!发生了什么事?

我需要循环,所以我可以有多个变量。

1 个答案:

答案 0 :(得分:0)

您应该尝试使用CATextLayer而不是创建UILabel并使用他们的图层。