iphone - CoreText 文本水平居中对齐

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

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

最佳答案

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

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

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

关于iphone - CoreText 文本水平居中对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9752893/

相关文章:

iphone - iOS开发中,可以读取 map 流量数据吗?

iOS - 基于设备的不同图像或缩放相同的图像?

ios - 程序化导航后退按钮未显示

iOS后台Airplay

objective-c - locationServicesEnabled == YES,但 [[CLLocationMagager alloc] init] 返回 nil

iphone - 我可以阻止 UITableViewCell 自动调整其 subview 的大小吗?

iphone - UITableView - 突出显示选定的单元格 [iOS]

ios - 使用 AIR 在 iOS 上流式传输 AAC+(在 FLV 内)

iphone - 显示 UIAlertView 时播放本地通知默认声音?

iphone - ABMultiValueRef 上的 iOS 地址簿错误