2013-09-22 213 views
45

在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]; 

我添加到字典什麼鍵值對獲得NSLineBreakByTruncatingTailNSTextAlignmentRight

回答

136

有一個鍵可以設置文本的段落樣式(包括換行方式,文本對齊方式等)。

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

你是怎麼找到的? +1 – ViruMax

+0

雖然我無法想象一個更短的變化 - 這當然有效,但似乎是分配工作只是爲了增加一些理由! –

+0

如何讓字符串多行? –

4

的代碼會這樣:

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];