如何在swift
中从本机swift String或NSString创建CFString let path:String = NSBundle.mainBundle().pathForResource(name.stringByDeletingPathExtension, ofType:"pdf")
let string:CFString = ??? path
let url:CFURLRef = CFURLCreateWithFileSystemPath(allocator:kCFAllocatorDefault, filePath:string, pathStyle:CFURLPathStyle.CFURLPOSIXPathStyle, isDirectory:false)
答案 0 :(得分:35)
投下它:
var str = "Hello, playground" as CFString
NSString(format: "type id: %d", CFGetTypeID(str))
答案 1 :(得分:27)
如果要转换非文字字符串,则必须将其强制转换为NSString。
let replacement = "World"
let string = "Hello, \(replacement)"
let cfstring:CFString = string as NSString
Swift知道如何将swift字符串转换为NSString,将NSString转换为CFString,但似乎不知道如何在一个中执行这两个步骤。
答案 2 :(得分:4)
您可以在CFString和NSString之间或NSString和String之间进行转换。诀窍是你必须在CFString和String之间进行双重演绎。
这有效:
var cfstr: CFString = "Why does Swift require double casting!?"
var nsstr: NSString = cfstr as NSString
var str: String = nsstr as String
这会给出错误"' CFString'不是' NSString'":
的子类型var cfstr: CFString = "Why does Swift require double casting!?"
var str: String = cfstr as String
答案 3 :(得分:3)
今天我尝试在操场上测试C API并import Foundation
使"string" as CFString
工作。
答案 4 :(得分:0)
如果您正在尝试将包含Swift字符串的变量转换为CFS字符串,我认为@freytag会用他的解释对其进行修改。
如果有人想看一个例子,我想我会包含一个代码片段,我将一个Swift字符串(" ArialMT"在这种情况下)转换为NSString,以便与之一起使用Core Text的CTFontCreateWithName函数(需要CFString)。 (注意:从NSString到CFString的转换是隐式的)。
// Create Core Text font with desired size
let coreTextFont:CTFontRef = CTFontCreateWithName("ArialMT" as NSString, 25.0, nil)
// Center text horizontally
var paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.Center
// Center text vertically
let fontBoundingBox: CGRect = CTFontGetBoundingBox(coreTextFont)
let frameMidpoint = CGRectGetHeight(self.frame) / 2
let textBoundingBoxMidpoint = CGRectGetHeight(fontBoundingBox) / 2
let verticalOffsetToCenterTextVertically = frameMidpoint - textBoundingBoxMidpoint
// Create text with the following attributes
let attributes = [
NSFontAttributeName : coreTextFont,
NSParagraphStyleAttributeName: paragraphStyle,
kCTForegroundColorAttributeName:UIColor.whiteColor().CGColor
]
var attributedString = NSMutableAttributedString(string:"TextIWantToDisplay", attributes:attributes)
// Draw text (CTFramesetterCreateFrame requires a path).
let textPath: CGMutablePathRef = CGPathCreateMutable()
CGPathAddRect(textPath, nil, CGRectMake(0, verticalOffsetToCenterTextVertically, CGRectGetWidth(self.frame), CGRectGetHeight(fontBoundingBox)))
let framesetter: CTFramesetterRef = CTFramesetterCreateWithAttributedString(attributedString)
let frame: CTFrameRef = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attributedString.length), textPath, nil)
CTFrameDraw(frame, context)