swift - Swift 中 CoreText CTFrameGetLineOrigins 的问题

标签 swift core-text

我有以下代码在 Objective-C 中运行

NSArray *lines = (NSArray *)CTFrameGetLines((__bridge CTFrameRef)columnFrame);
CGPoint origins[[lines count]];
CTFrameGetLineOrigins((__bridge CTFrameRef)columnFrame, CFRangeMake(0, 0), origins);

但是当移植到 Swift 时,编译器会提示 Cannot convert the expression´s ´Void´to type ´CMutablePointer<CGPoint>CTFrameGetLineOrigins线

let nsLinesArray: NSArray = CTFrameGetLines(ctFrame) // Use NSArray to bridge to Array
let ctLinesArray = nsLinesArray as Array
var originsArray: Array<CGPoint> = CGPoint[]()
//var originsArray: NSMutableArray = NSMutableArray.array()
let range: CFRange = CFRangeMake(0, 0)
CTFrameGetLineOrigins(ctFrame, range, originsArray)

我必须在 CGFrameGetLines 中使用 NSArray函数,然后转换为 Swift 数组,并检查 ctLinesArray,显示 CTLine正确检索对象

我尝试使用NSMutableArray对于 originsArray,结果相同。

知道缺少什么吗?

最佳答案

您必须添加地址运算符 &将指针传递给 originsArray 的开始到函数:

CTFrameGetLineOrigins(ctFrame, range, &originsArray)

引用:Interacting with C APIs 在《使用 Swift 与 Cocoa 和 Objective-C》一书中:

C Mutable Pointers

When a function is declared as taking a CMutablePointer<Type> argument, it can accept any of the following:

  • ...
  • An in-out Type[] value, which is passed as a pointer to the start of the array, and lifetime-extended for the duration of the call.

来自 Expressions在《Swift 编程语言》一书中:

In addition to the standard library operators listed above, you use & immediately before the name of a variable that’s being passed as an in-out argument to a function call expression.

一个补充(@eharo2 已经弄清楚了),originsArray必须有空间 必要数量的元素,可以通过以下方式实现

var originsArray = CGPoint[](count:ctLinesArray.count, repeatedValue: CGPointZero)

关于swift - Swift 中 CoreText CTFrameGetLineOrigins 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24434853/

相关文章:

使用 Realm 和 RAC 进行 Swift 单元测试

json - 将 json 响应转换为 Realm 对象

ios - Swift - 如何从枚举变量获取枚举大小写参数?

ios - 如果我想要格式化文本但不想使用 UIWebView,那么 Core Text 是我唯一剩下的选择吗?

ios - 核心文本 - 如何知道文本是否从右到左

IOS 本地化声音文件无法在设备上运行

ios - 使用 CoreText 和 CTFontDescriptor 设置字体粗细

cocoa - 将 HTML 加载到 NSTextView 时设置默认字体和大小

ios - 多页核心文本解析器(单列)

ios - 无法在按钮和 UIView 周围创建阴影