2012-03-17 163 views
1

我正在使用CoreText,並且我想讓它使我的NSMutableAttributedString始終居中對齊其文本。這是我使用的代碼,它不工作:CoreText文本水平居中對齊

CTTextAlignment paragraphAlignment = kCTCenterTextAlignment; 
    CTParagraphStyleSetting paragraphSettings[1] = {{kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment), &paragraphAlignment}}; 
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(paragraphSettings, 1); 

text = [[NSMutableAttributedString alloc] initWithString:@"" attributes:[NSDictionary dictionaryWithObjectsAndKeys: (id)paragraphStyle, (NSString*)kCTParagraphStyleAttributeName, nil]]; 

有沒有人有任何想法如何正確地做到這一點?

+0

顯示文本的其餘代碼是什麼? (答案取決於你使用的例程)。 – lnafziger 2012-03-17 22:19:56

+1

http://stackoverflow.com/questions/6801856/iphone-nsattributedstring-add-text-alignment/6801901#6801901應該回答你的問題。 – 2013-02-12 23:45:24

回答

0

如果您的應用程序與10.10或更高版本兼容,則不使用CoreText的其他解決方案是使用NSParagraphStyle。

NSMutableParagraphStyle *rectStyle = NSMutableParagraphStyle.defaultParagraphStyle.mutableCopy; 
rectStyle.lineBreakMode = NSLineBreakByClipping; 
rectStyle.alignment = NSTextAlignmentCenter; 

NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:myText attributes:@{NSParagraphStyleAttributeName : rectStyle}];