我试图从此处转换以下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 );
// ...
}
进入Swift:
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使用&
语法,因此我不知道问题所在。如何解决此错误?
答案 0 :(得分:7)
ascent
和descent
必须是变量才能传递
作为&
的进出参数:
var ascent: CGFloat = 0
var descent: CGFloat = 0
let line: CTLineRef = CTLineCreateWithAttributedString(asp)
let width = CGFloat(CTLineGetTypographicBounds(line, &ascent, &descent, nil))
从CTLineGetTypographicBounds()
返回时,这些变量将设置为
线的上升和下降。另请注意,此函数返回
Double
,因此您需要将其转换为CGFloat
。