2012-03-17 187 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}];