Как отобразить многострочный UILabel с помощью NSMutableAttributedString


Я пытаюсь создать многострочный UILabel с NSMutableAttributedString. Это прекрасно работает, когда я присваиваю атрибут полной строке следующим образом:

UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,100)];
[contentLabel setLineBreakMode:NSLineBreakByWordWrapping];
[contentLabel setNumberOfLines:0];
[contentLabel setFont:[UIFont systemFontOfSize:13];

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"hello I am a long sentence that should break over multiple lines"];
[string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13] range:NSMakeRange(0, [string length])];

contentLabel.attributedText = string;

Но мне нужно применить ряд атрибутов для различных поддиапазонов NSAttributedString (выделять жирным шрифтом определенные слова).

UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,100)];
[contentLabel setLineBreakMode:NSLineBreakByWordWrapping];
[contentLabel setNumberOfLines:0];
[contentLabel setFont:[UIFont systemFontOfSize:13];

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"hello I am a long sentence that should break over multiple lines"];
[string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13] range:NSMakeRange(3, 5)];

contentLabel.attributedText = string;

Я нахожу, что если я сделаю это,текст больше не будет отображаться на нескольких строках в метке. Он отображается в виде одной линии, центрированной вертикально в центре экрана. рамка этикетки.

Есть ли что-то, что я упускаю здесь?
2 13

2 ответа:

Как обсуждалось в комментариях к вопросу, код, представленный в вопросе, на самом деле работает правильно и действительно отображает приписываемую строку, как и предполагалось. (Проблема была в другом месте моего кода)

Я часто использую UITextView и присваиваю ему текст, приписываемый аналогичным образом:

        // creiamo textView descrizione
    UITextView *description = [[UITextView alloc] init];
    description.frame = CGRectMake(20, 453, 500, 190);

    NSDictionary *attribute1 = @{NSForegroundColorAttributeName: [UIColor blackColor],
                                     NSBackgroundColorAttributeName: [UIColor clearColor],
                                     NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Bold" size:22.0],
                                     };

    NSDictionary *attribute2 = @{NSForegroundColorAttributeName: [UIColor blackColor],
                                        NSBackgroundColorAttributeName: [UIColor clearColor],
                                        NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:10],
                                        };

    NSDictionary *attribute3 = @{NSForegroundColorAttributeName: [UIColor blackColor],
                                           NSBackgroundColorAttributeName: [UIColor clearColor],
                                           NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14.0]
                                           };

    NSMutableAttributedString *info = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ %@ %@ \n\n%@ \n     ", string1, string2 , string3, string4]];

    [info setAttributes:attribute1 range:NSMakeRange(0, ([string1 length]))];
    [info setAttributes:attribute2 range:NSMakeRange(([string1 length]),([string2 length]+[string3 length]))];
    [info setAttributes:attribute3 range:NSMakeRange(([string1 length] [string2 length]+[string3 length]), [string4 length])];

    description.attributedText = info;
    description.backgroundColor = [UIColor clearColor];
    description.editable = NO;
    description.textColor = [UIColor blackColor];
    [viewInfo addSubview:description];
    [description sizeToFit];