我正在使用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]];


有谁知道如何正确执行此操作?

最佳答案

如果您的应用程序与10.10或更高版本兼容,则不使用CoreText的其他解决方案是使用NSParagraphStyle。

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

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

10-05 20:04