I have a UIView with it’s subclass set in interface builder to a UIView subclass I created. I want to update labels within the UIView class holding them. I cannot seem to update the text of any labels drawn in drawRect. What are my options for drawing elements I need to change within a UIView subclass?
// Using UILabel subclass (FontLabel)
- (void)drawRect:(CGRect)rect {
scoreLabel = [[FontLabel alloc] initWithFrame:CGRectMake(0,0, 400, 50) fontName:@"Intellect" pointSize:80.0f];
scoreLabel.textColor = [[UIColor alloc] initWithRed:0.8157 green:0.8000 blue:0.0706 alpha:1.0f];
[scoreLabel sizeToFit];
[scoreLabel setText:@"Initial text"];
[self addSubview:scoreLabel];
[self setNeedsDisplay];
//Also tried [self setNeedsLayout];
}
- (void)updateScoreLabel:(int)val
{
[scoreLabel setText:[NSString stringWithFormat:@"%d", val]];
}
// Using CATextLayer
- (void)drawRect:(CGRect)rect {
scoreLabel = [CATextLayer layer];
[scoreLabel setForegroundColor:[UIColor whiteColor].CGColor];
[scoreLabel setFrame:CGRectMake(0,0, 200, 20)];
[scoreLabel setAlignmentMode:kCAAlignmentCenter];
[[self layer] addSublayer:scoreLabel];
[scoreLabel setString:@"Initial text"];
[self setNeedsDisplay];
//Also tried [self setNeedsLayout];
}
- (void)updateScoreLabel:(int)val
{
[scoreLabel setString:[NSString stringWithFormat:@"%d", val]];
}
In order to change the text of labels programmatically, you need to do the following:
In your .h file:
Define them as
UILabels in your @interface sectionAdd
IBOutlets to them in your @property declarationsIn your .m file:
After that, you can refer to them as any other
self.variable, and set theirtextproperty to change how they appear in your display.In general, trying to subclass
UIViewcan be a bit tricky (as you’re finding), but hopefully the above will help you at least a bit.