Is there a constant for the maximum CGFloat value?

前端 未结 8 801
滥情空心
滥情空心 2021-02-02 05:09

I need to create a CGSize to compute text height of an arbitrary text with arbitrary length. UIKit has this nice method -sizeWithFont:constrainedToSize: and my text is only cons

8条回答
  •  感情败类
    2021-02-02 06:13

    This is more of a comment than an answer however I don't have enough reputation to comment at the present.

    I just came across unexpected behavior with using CGFLOAT_MAX: on an iPhone 5S (64bit) device running iOS 7.1.2 and using Xcode 5.1.1, the following code:

    CGFloat numRot = floorf(CGFLOAT_MAX / 360.0);
    NSLog(@"numRot = %.2f", numRot);
    

    Outputs:

    numRot = inf
    

    Whereas, this code:

    CGFloat numRot = floorf(FLT_MAX / 360.0);
    NSLog(@"numRot = %.2f", numRot);
    

    Correctly outputs:

    numRot: 945228740662580166143622731901435904.00
    

    I command+clicked on the CGFLOAT_MAX and Xcode took me to the CoreGraphics frameworks CGBase.h file with the following macro definition:

    # define CGFLOAT_MAX DBL_MAX
    

    I command+clicked on CGFloat and Xcode took me to another line in the same file:

    typedef CGFLOAT_TYPE CGFloat;
    

    Then I command+clicked on the CGFLOAT_TYPE and it jumped to the #define line here:

    #if defined(__LP64__) && __LP64__
    # define CGFLOAT_TYPE double
    ...
    

    So, for some reason my CGFloat variable is supposed to be a double, however it appears to be a float that overflows when it gets assigned a double value (i.e. CGFLOAT_MAX). As far as I can tell this Apple documentation page indicates using %f with NSLog should print the double - someone please correct me if this is wrong.

    All that to say, if FLT_MAX works for your case, you may want to stick with that for now instead of CGFLOAT_MAX, especially if you are relying on a library that specifically accept float arguments instead of double or CGFloat.

提交回复
热议问题