CoreText - 如何在框架内居中放置文本?

CoreText - how to center text within frame?

我试图将 CoreText 居中,我发现的最好的例子是 blog post. However, I was working with NSAttributedString, and although the CFMutableAttributedStringReference should be toll-free bridged 到 NSMutableAttributedString,当我尝试在我的 drawRect方法:

NSMutableAttributedString* attString = [[NSMutableAttributedString alloc]
                                  initWithString:[NSString stringWithFormat:@"%d %@", self.currentNum, self.units]]; //2


//    set paragraph style attribute
CFAttributedStringSetAttribute(attString, CFRangeMake(0, CFAttributedStringGetLength(attrStr)), kCTParagraphStyleAttributeName, paragraphStyle);

//    set font attribute
CFAttributedStringSetAttribute(attString, CFRangeMake(0, CFAttributedStringGetLength(attrStr)), kCTFontAttributeName, font);

特别是,我在最后两行中遇到了相同的构建错误:

Incompatible pointer types passing retainable parameter of type 'NSMutableAttributedString'__strong to a CF function expecting 'CFMutableAttributedStringRef' (aka 'struct __CFAttributedString *') type.

我知道免费桥接不必倒退,但是我如何设置 NSMutableAttributedString 的对齐方式以使其在提供的框架中居中?我事先不知道文字或文字的大小,所以我需要能够将它居中,以便它在各种尺寸下看起来都不错。

感谢您的任何建议。

您必须按照 Casting and Object Lifetime Semantics 中的说明转换免费桥接类型。

引用:

Through toll-free bridging, in a method where you see for example an NSLocale * parameter, you can pass a CFLocaleRef, and in a function where you see a CFLocaleRef parameter, you can pass an NSLocale instance. You also have to provide other information for the compiler: first, you have to cast one type to the other; in addition, you may have to indicate the object lifetime semantics.

示例:

CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attString, …

或者,您可以使用 NSMutableAttributedString 的方法来添加属性。