Подтвердить что ты не робот

Как визуализировать многострочный 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;

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

Я здесь что-то не хватает?

4b9b3361

Ответ 1

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

Ответ 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];