我必须在swift(文档链接)中使用 CFDictionaryCreate
方法。
我很难正确地初始化输入参数,以便通过类型UnsafeMutablePointer<UnsafePointer<Void>>
的参数(键和值)。
这是我的代码:
var font_name: CFStringRef! = CFStringCreateWithCString(nil, "Courier", kCFStringEncodingASCII)
var font: CTFontRef! = CTFontCreateWithName(font_name, 25.0, nil)
var keys: [UnsafePointer<Void>] = ???? // how to intialize with "kCTFontAttributeName"
var values: [UnsafePointer<Void>] = ???? // how to intialize with "font" variable
var keyCallBacks = kCFTypeDictionaryKeyCallBacks
var valueCallBacks = kCFTypeDictionaryValueCallBacks
var font_attributes: CFDictionaryRef! = CFDictionaryCreate(kCFAllocatorDefault, &keys, &values, sizeofValue(keys), &keyCallBacks, &valueCallBacks)
var attr_string: CFAttributedStringRef! = CFAttributedStringCreate(nil, "hello", font_attributes)
您可以简单地使用[ NSString : AnyObject ]
类型的Swift字典,该字典自动桥接到NSDictionary
或 CFDictionary
。请注意,您也不需要CFStringRef
。
let font = CTFontCreateWithName("Courier", 25.0, nil)
let attributes : [ NSString : AnyObject ] = [ kCTFontAttributeName : font ]
let attrString = CFAttributedStringCreate(nil, "Hello", attributes)
或者,
let attrString = NSAttributedString(string: "Hello", attributes: attributes)
因为 NSAttributedString
是免费的 CFAttributedString
。
只是为了完整,这是您可以使用的方式 CFDictionaryCreate()
:
let font = CTFontCreateWithName("Courier", 25.0, nil)
var keys = [ unsafeAddressOf(kCTFontAttributeName) ]
var values = [ unsafeAddressOf(font) ]
var keyCallbacks = kCFTypeDictionaryKeyCallBacks
var valueCallbacks = kCFTypeDictionaryValueCallBacks
let attributes = CFDictionaryCreate(nil, &keys, &values, 1, &keyCallbacks, &valueCallbacks)
let attrString = CFAttributedStringCreate(nil, "Hello", attributes)