V.J
V.J

Reputation: 189

How to show multiple line text that has different font without using multiple Labels

I have to show a text paragraph that contains few words in bold font. ex.

enter image description here

If I use different labels then on changing the orientation it does not resize properly.

Can anyone tell me what can the best way to do it.

Upvotes: 0

Views: 81

Answers (3)

Antonio MG
Antonio MG

Reputation: 20410

You have to use a NSAttributedString and assign it to the UITextField, this is an example:

UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
UIFont *regularFont = [UIFont systemFontOfSize:fontSize];

NSMutableAttributedString *myAttributedString = [[NSMutableAttributedString alloc] initWithString:yourString];
[myAttributedString addAttribute:NSFontAttributeName
                      value:boldFont
                      range:NSMakeRange(0, 2)];
[myAttributedString addAttribute:NSFontAttributeName
                      value:regularFont
                      range:NSMakeRange(3, 5)];
[self.description setAttributedText:myAttributedString];

Find all the doc here:

NSAttributedString

Upvotes: 1

Tarek Hallak
Tarek Hallak

Reputation: 18470

For your case, you can use a webView and load it with your string:

[webView loadHTMLString:[NSString stringWithFormat:@"<html><body style=\"background-color: transparent;\">This is <b><i>Test</b></i> dummy text ..</body></html>"] baseURL:nil];

Upvotes: 0

Jordan Montel
Jordan Montel

Reputation: 8247

You can use an UITextView using NSAttributedString (have a look to the apple doc)

And you have an explanation of how to use it here.

You can find the range of your word and change the font or the color or whatever using :

- (IBAction)colorWord:(id)sender {
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:self.text.text];

    NSArray *words = [self.text.text componentsSeparatedByString:@" "];

    for (NSString *word in words) 
    {        
        if ([word hasPrefix:@"@"]) 
        {
            NSRange range=[self.text.text rangeOfString:word];
            [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];           
        }
    }
    [self.text setAttributedText:string];
}

Upvotes: 1

Related Questions