How to pass UIFont object to CTFont in Swift

I am trying to port some code to Swift that uses UIFont and CTFont , and that (successfully, in Objective-C) uses simple bridge translations to go from one to the other and vice versa.

For example, consider this code (in the UIFontDescriptor category):

 UIFont *font = [UIFont fontWithDescriptor:self size:0.0]; NSArray *features = CFBridgingRelease(CTFontCopyFeatures((__bridge CTFontRef)font)); 

I have not yet been able to figure out how to express this in Swift in a way that will be compiled. At least the following:

 let font = UIFont(descriptor:self, size: 0.0) let features = CTFontCopyFeatures(font as CTFont) 

Error: 'UIFont' does not convert to 'CTFont'

+8
uikit swift core-text
source share
2 answers

This seems to have been fixed in a later version of Swift and / or CoreText . At least now it works in my testing using Xcode 7.0.1.

+1
source share

Try it. You cannot just force values ​​from one type to another. If you create a CTFont from the descriptor and size, this seems to give you a valid array, even if you don't include the transformation matrix (parameter nil)

 let font = CTFontCreateWithFontDescriptor(descriptor, 0.0, nil) let features: NSArray = CTFontCopyFeatures(font) 

Regarding creating a CTFontDescriptor, I would use CTFontDescriptorCreateWithNameAndSize or CTFontDescriptorCreateWithAttributes depending on what you originally gave. The latter takes up a simple NSDictionary, while the former simply uses the name and font size.

To switch from an existing font (name it originalFont ), simply do the following to get the handle:

 let font = CTFontCreateWithName(originalFont.fontName as CFStringRef, originalFont.pointSize as CGFloat, nil) 
+1
source share

All Articles