-->

Change text color of WKInterfaceLabel using NSMuta

2020-07-22 18:49发布

问题:

I'm trying to change text color in WKInterfaceLabel using setAttributedText property. Here's the code:

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];

The result:

Only the first attribute works correctly. I've done some tests but nothing happens, the color font doesn't change to red.

WKInterfaceController code:

@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:

Could you post your full interface controller and the row controller? It's very difficult to tell what could be wrong. What you are doing at the moment looks fine. With that said, there are two things that may help here.

First, make sure not to try to set this in init or awakeWithContext. You need to set this in willActivate. Otherwise you will get some odd behavior.

Second, you need to set this when the interface controller is visible. Otherwise the change may not get picked up.