2013-10-05 23 views
25

有一個方法什麼是iOS 7中的NSLineBreakMode等效的字符串繪製方法?

- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode alignment:(NSTextAlignment)alignment; 

我必須代替現在的iOS 7,我得到儘可能

NSDictionary *attributes = @{NSFontAttributeName: font}; 
[self drawInRect:rect withAttributes:attributes]; 

但如何指定比如文字換行模式換?我搜索了Attributed字符串繪圖符號的文檔,但沒有提到換行符模式。這是自動的總是自動換行嗎?

回答

49

您需要創建段落樣式。

NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; 
[style setLineBreakMode:NSLineBreakByWordWrapping]; 

NSDictionary *attributes = @{NSFontAttributeName: font, NSParagraphStyleAttributeName: style}; 
[self drawInRect:rect withAttributes:attributes]; 

點擊此處瞭解詳情: https://developer.apple.com/documentation/uikit/nsparagraphstyle?language=objc

+0

我想你也可以用'[NSMutableParagraphStyle的alloc]初始化]'代替可變副本。 –

6

在SWIFT:

let style = NSMutableParagraphStyle() 
style.lineBreakMode = .ByWordWrapping 

let attributes: [String: AnyObject] = [ 
    NSFontAttributeName: font, 
    NSParagraphStyleAttributeName: style 
] 
相關問題