首页 文章

更新UIView子类中drawRect中绘制的组件中的文本

提问于
浏览
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]];
}

1 回答

  • 0

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

    在你的.h文件中:

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

    • 在@property声明中为它们添加 IBOutlet

    在.m文件中:

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

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

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

相关问题