【发布时间】:2016-03-18 05:58:42
【问题描述】:
我正在尝试从中转换以下 Objective-C 代码 (source)
-(CGRect) dimensionsForAttributedString: (NSAttributedString *) asp {
CGFloat ascent = 0, descent = 0, width = 0;
CTLineRef line = CTLineCreateWithAttributedString( (CFAttributedStringRef) asp);
width = CTLineGetTypographicBounds( line, &ascent, &descent, NULL );
// ...
}
进入斯威夫特:
func dimensionsForAttributedString(asp: NSAttributedString) -> CGRect {
let ascent: CGFloat = 0
let descent: CGFloat = 0
var width: CGFloat = 0
let line: CTLineRef = CTLineCreateWithAttributedString(asp)
width = CTLineGetTypographicBounds(line, &ascent, &descent, nil)
// ...
}
但我在这一行中收到&ascent 的错误:
width = CTLineGetTypographicBounds(line, &ascent, &descent, nil)
'&' 与 'UnsafeMutablePointer' 类型的非 inout 参数一起使用
Xcode 建议我通过删除& 来修复它。但是,当我这样做时,我得到了错误
无法将“CGFloat”类型的值转换为预期的参数类型“UnsafeMutablePointer”
Interacting with C APIs documentation 使用& 语法,所以我看不出问题出在哪里。如何解决此错误?
【问题讨论】:
-
CTLineGetTypographicBounds函数需要一个UnsafeMutablePointer<CGFloat>,因此例如使用withUnsafeMutablePointer,您应该创建一个UnsafeMutablePointer<CGFloat>,并将其用作输入参数。 -
我的问题是我没有使用
var关键字将它们声明为变量。
标签: ios objective-c swift unsafe-pointers