iosobjective-cxcodecolorsnslocalizedstring

How can I change color of part of the text in a NSLocalizedString with Objective C?


Here is my problem. I have a ViewController in which there is a label with a text and I want to change the color of some of the words in that sentence. The string is an NSLocalizedString which is written in different languages and changes based on the user system language.

    self.welcomeMessageLabel.text = NSLocalizedString(@"welcome_message", nil);

This is the result that I want to achieve. enter image description here

How can I color part of the text?


Solution

  • #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        _welcomeMessageLabel.attributedText = [self attributedString1];
    }
    
    
    - (NSAttributedString *)attributedString1 {
        NSString *string = @"Ti abbiamo inviato un link all'inndirizzo email che";
        NSString *substring1 = @"link";
        NSString *substring2 = @"email";
        
    //    NSString *string = NSLocalizedString(@"welcome_message", nil);
    //    NSString *substring1 = NSLocalizedString(@"welcome_message_substring1", nil);
    //    NSString *substring2 = NSLocalizedString(@"welcome_message_substring2", nil);
    
    
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString: string];
        NSDictionary *attributes = @{NSForegroundColorAttributeName: [UIColor orangeColor]};
        
        [attributedString
         replaceCharactersInRange:[string rangeOfString:substring1]
         withAttributedString:[[NSAttributedString alloc] initWithString: substring1 attributes:attributes]
         ];
        
        [attributedString
         replaceCharactersInRange:[string rangeOfString:substring2]
         withAttributedString:[[NSAttributedString alloc] initWithString: substring2 attributes:attributes]
         ];
        
        return  attributedString;
    }
    
    @end

    enter image description here