CoreText水平中心对齐文本

时间:2012-03-17 19:08:46

标签: iphone ios cocoa-touch core-graphics core-text

我正在使用CoreText我希望这样做,以便NSMutableAttributedString始终将其文字对齐。这是我正在使用的代码,它不起作用:

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

有没有人知道如何正确地做到这一点?

1 个答案:

答案 0 :(得分: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}];