How can I tell Swift to use "no" NSStringDrawingOptions
In Objective-C I managed to make a call like this, i.e. pass options "no":
[string boundingRectWithSize:size options:0 attributes:attributes context:nil]
How can I specify an appropriate call in Swift to do the same. For example, transfer NSStringDrawingOptions(rawValue: 0)!
raises a runtime error.
source to share
If you look at the Objective-C header , you will notice that it is NSStringDrawingOptions
declared as NS_ENUM
, so it converts as enum
in Swift (versus NS_OPTIONS
which converts to struct
).
typedef NS_ENUM(NSInteger, NSStringDrawingOptions) {
NSStringDrawingTruncatesLastVisibleLine = 1 << 5, // Truncates and adds the ellipsis character to the last visible line if the text doesn't fit into the bounds specified. Ignored if NSStringDrawingUsesLineFragmentOrigin is not also set.
NSStringDrawingUsesLineFragmentOrigin = 1 << 0, // The specified origin is the line fragment origin, not the base line origin
NSStringDrawingUsesFontLeading = 1 << 1, // Uses the font leading for calculating line heights
NSStringDrawingUsesDeviceMetrics = 1 << 3, // Uses image glyph bounds instead of typographic bounds
} NS_ENUM_AVAILABLE_IOS(6_0);
Because of this, you cannot set it in Swift to any other value than the available enumeration cases (without getting a runtime error).
As @rintaro pointed out in the comments above, this is considered a bug in iOS (this is allowed in OS X 10.10)
source to share
I have an answer from Apple Developer Relations regarding this (I raised a related bug).
The answer is that you pass an empty set of options [] when you don't need any parameters.
function definition (swift3):
boundingRect(with size: NSSize, options: NSStringDrawingOptions = [], attributes: [String : AnyObject]? = [:]) -> NSRect
So
str.boundingRect(with:NSSize(width: 100, height: 100), options:[], attributes: [:])
or, as empty values ββhave default values ββin the method definition, you can omit them entirely - as simple as:
str.boundingRect(with:NSSize(width: 100, height: 100))
source to share