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

Выровнять текст с помощью drawInRect: withAttributes:

В версии моего приложения iOS 5 у меня было:

[self.text drawInRect: stringRect
             withFont: [UIFont fontWithName: @"Courier" size: kCellFontSize]
        lineBreakMode: NSLineBreakByTruncatingTail
            alignment: NSTextAlignmentRight];

Я обновляюсь для iOS 7. Вышеупомянутый метод устарел. Теперь я использую drawInRect: withAttributes:. Параметр атрибутов является объектом NSDictionary. Я могу получить drawInRect: withAttributes: работать для прежнего параметра шрифта, используя это:

      UIFont *font = [UIFont fontWithName: @"Courier" size: kCellFontSize];

      NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: font, NSFontAttributeName,
                                  nil];

      [self.text drawInRect: stringRect
             withAttributes: dictionary];

Какие пары ключевого значения я добавляю в словарь для получения NSLineBreakByTruncatingTail и NSTextAlignmentRight?

4b9b3361

Ответ 1

Существует один ключ для установки стиля абзаца текста (включая режим прерывания строки, выравнивание текста и т.д.).

Из docs:

NSParagraphStyleAttributeName

Значение этого атрибута - это объект NSParagraphStyle. Используйте этот атрибут для применения нескольких атрибутов к диапазону текста. Если этот атрибут не указан, строка использует атрибуты абзаца по умолчанию, возвращаемые методом defaultParagraphStyle NSParagraphStyle.

Итак, вы можете попробовать следующее:

UIFont *font = [UIFont fontWithName:@"Courier" size:kCellFontSize];

/// Make a copy of the default paragraph style
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
/// Set line break mode
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
/// Set text alignment
paragraphStyle.alignment = NSTextAlignmentRight;

NSDictionary *attributes = @{ NSFontAttributeName: font,
                    NSParagraphStyleAttributeName: paragraphStyle };

[text drawInRect:rect withAttributes:attributes];

Ответ 2

Код идет следующим образом:

CGRect textRect = CGRectMake(x, y, length-x, maxFontSize);
UIFont *font = [UIFont fontWithName:@"Courier" size:maxFontSize];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;


   paragraphStyle.alignment = NSTextAlignmentRight;
    NSDictionary *attributes = @{ NSFontAttributeName: font,
                                  NSParagraphStyleAttributeName: paragraphStyle,
                                  NSForegroundColorAttributeName: [UIColor whiteColor]};
[text drawInRect:textRect withAttributes:attributes];