使用NSMutableAttributedString更改WKInterfaceLabel的文本颜色

3
我正在尝试使用setAttributedText属性更改WKInterfaceLabel的文本颜色。以下是代码:
MyRowController *row = [self.interfaceTable rowControllerAtIndex:idx];

NSString *str_tmp = @"Test";

NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:str_tmp];        
[text addAttribute:NSFontAttributeName value:[UIFont fontWithName:FONT_REGULAR size:12.0] range:NSMakeRange(0, str_tmp.length)];
[text addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, str_tmp.length)];

[row.lines setAttributedText:text];

结果如下:

结果:

在此处输入图片描述

只有第一个属性能够正确工作。我进行了一些测试,但是没有任何反应,颜色字体不会变成红色。

WKInterfaceController 代码:

@interface MyInterfaceController()

@implementation MyInterfaceController

- (void)awakeWithContext:(id)context {

    [super awakeWithContext:context];

}

- (void)willActivate {

    [super willActivate];
    [self loadTableData];

}

- (void)didDeactivate {
    [super didDeactivate];
}


#pragma mark - 
#pragma mark Table
#pragma mark -

- (void)loadTableData {

    NSMutableArray *arrItems = [NSMutableArray new];

    for(user* usr in self.agenda.users){
        [arrItems addObject:usr];
    }

    [self.interfaceTable setNumberOfRows:arrItems.count withRowType:@"userRow"];

    [arrItems enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL *stop) {

        MyRowController *row = [self.interfaceTable rowControllerAtIndex:idx];

        NSString *str_tmp = @"Test";

        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:str_tmp];        
        [text addAttribute:NSFontAttributeName value:[UIFont fontWithName:FONT_REGULAR size:12.0] range:NSMakeRange(0, str_tmp.length)];
        [text addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, str_tmp.length)];

        [row.lines setAttributedText:text];

    }];

}

@end

MyRowController code:

@import WatchKit;

@interface MyRowController : NSObject

@property (weak, nonatomic) IBOutlet WKInterfaceSeparator *separator;
@property (weak, nonatomic) IBOutlet WKInterfaceGroup *contentGroup;
@property (weak, nonatomic) IBOutlet WKInterfaceLabel *lines;
@property (weak, nonatomic) IBOutlet WKInterfaceGroup *separatorBottom;


@end
1个回答

2

您能否发布完整的接口控制器和行控制器?很难确定哪里出了问题。你现在所做的看起来很好。话虽如此,这里有两件事可能会有所帮助。

首先,请确保不要在 initawakeWithContext 中尝试设置它。您需要在 willActivate 中设置它。否则,您将得到一些奇怪的行为。

其次,您需要在界面控制器可见时设置此项。否则,更改可能不会被捕捉到。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接