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

时间:2015-11-20 18:49:03

标签: ios objective-c

我正在尝试将CoreText集中在一起,我找到的最好的例子是blog post。但是,我正在使用NSAttributedString,虽然CFMutableAttributedStringReference应该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的对齐以使其在提供的框架中居中?我事先并不知道文本的文字或大小,所以我需要能够将它放在中心位置,以便它能以各种尺寸显示。

感谢您的任何建议。

1 个答案:

答案 0 :(得分:0)

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

引用:

  

通过免费桥接,在您看到例如NSLocale *参数的方法中,您可以传递CFLocaleRef,并且在您看到CFLocaleRef参数的函数中,您可以传递NSLocale实例。您还必须为编译器提供其他信息:首先,您必须将一种类型转换为另一种类型;此外,您可能必须指出对象的生命周期语义。

示例:

CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attString, …

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