From Objective-C to Swift, you must know the (two) combination of options

From Objective-C to Swift, you must know the (two) combination of options

Anyone who has used Options knows that a few vertical lines put these values ​​together. such as:

?
1
2
3
4
5
+ (NSStringDrawingOptions)combine{
     return NSStringDrawingTruncatesLastVisibleLine |
             NSStringDrawingUsesLineFragmentOrigin |
             NSStringDrawingUsesFontLeading;
}

 A very simple thing. Why do you need to take out an article specifically? Because APPLE has bugs! Yes, you will get an error if you do this in Swift (you know what I said is written in Swift syntax). such as:

?
1
2
3
4
let size = CGSize(width: 280 , height: Int . max )
let options : NSStringDrawingOptions = .UsesLineFragmentOrigin | .UsesFontLeading
 
let boundingRect = string.bridgeToObjectiveC().boundingRectWithSize(size, options: options, attributes: attributes, context: nil)

 It's not working. The compiler will report an error: could not find memeber'UsesLineFragmentOrigin' . But the code still has to be written like this. This is the only way to write when it is necessary to satisfy these different options at the same time.

But what should I do if there is such a bug? Well, you can't find a ready-made solution with Xcode? Think about it, what will you think of? It must be OC. And it's very convenient, although it's still a detour, hey.

In a Swift project, when adding or importing an OC file, Xcode will prompt you to create a bridge header (bridge street file, let’s just call it bridge head). If the system does not give you a room, you can do it yourself, and then specify your own bridgehead path in the build settings. This specific will be explained in this series.

Then create the OC file, and then realize the functions you need, such as:

?
1
2
3
4
5
6
7
8
9
@implementation Utils
 
+ (NSStringDrawingOptions)combine{
     return NSStringDrawingTruncatesLastVisibleLine |
             NSStringDrawingUsesLineFragmentOrigin |
             NSStringDrawingUsesFontLeading;
}
 
@end

 I don't need to write the header files in detail. It just declares that the class name is Utils , and this class contains a class method called combine .

As long as there is this bridge in the file OC file header file import into, and then the Swift file can be used directly. You don't need to have import ideas and actions in any Swift code. When used like this:

?
1
2
3
let <strong>options< / strong> = Utils.combine()
let calculateSize = CGSize(width: width, height: 0 as Double)
var rect = content.boundingRectWithSize(calculateSize, options: <strong>options< / strong>, attributes: [NSFontAttributeName: font], context: nil)

 Very simple, this problem is solved. I will wait for Apple to fix his bug later.

Guess you like

Origin blog.csdn.net/Draven__/article/details/93234225