0

我有一个 UIView,它的子类在界面生成器中设置为我创建的 UIView 子类。我想更新持有它们的 UIView 类中的标签。我似乎无法更新在 drawRect 中绘制的任何标签的文本。我需要在 UIView 子类中更改的绘图元素有哪些选项?

// 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]];
}   
4

1 回答 1

0

为了以编程方式更改标签的文本,您需要执行以下操作:

在您的 .h 文件中:

  • UILabel在 @interface 部分中将它们定义为s

  • IBOutlet在你的 @property 声明中添加s

在您的 .m 文件中:

  • 在您的 .m 文件中为它们添加 @synthesize 行。

之后,您可以将它们称为任何其他self.变量,并设置它们的text属性以更改它们在显示中的显示方式。

一般来说,尝试子类UIView化可能有点棘手(正如您所发现的那样),但希望以上内容至少对您有所帮助。

于 2011-01-11T20:24:22.160 回答