2013-02-27 4 views
13

Я пытаюсь создать многострочный 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; 

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

Есть ли что-то, что мне не хватает здесь?

+1

Вы сделали этикетку достаточно высокой для второй линии? –

+0

Я не могу воспроизвести это на 6.1. Я отмечаю, что ваш код немного некорректен (отсутствует) в строке setFont: и вместо «contentLabel» вы используете «метку» в одном месте). Вы уверены, что это фактический код? –

+0

@ Кевин Баллард: Да, этикетка достаточно высока. – adriaan

ответ

4

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

1

Я использую часто 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]; 
Смежные вопросы