4

我正在尝试从中转换以下 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 文档使用&语法,所以我看不出问题出在哪里。如何修复此错误?

4

1 回答 1

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(),这些变量将设置为线的上升和下降。另请注意,此函数返回 a Double,因此您需要将其转换为CGFloat.

于 2015-12-12T10:04:09.460 回答