Objective C: NSRange or similar with float?

蹲街弑〆低调 提交于 2019-12-01 06:17:51

Although you could reuse one of several "pair objects" from the graphics library (you can pick from a CGPoint or CGSize, or their NS... equivalents) the structs behind these objects are so simple that it would be better to create your own:

typedef struct FPRange {
    float location;
    float length;
} FPRange;

FPRange FPRangeMake(float _location, float _length) {
    FPRange res;
    res.location = _location;
    res.length = _length;
    return res;
}

Yes, you can even go and look at the definitions of NSRange and NSMakeRange (in NSRange.h, easiest way to get there is to 'command click' on NSRange name in Xcode) to see how to do it:

typedef struct _NSRange {
    NSUInteger location;
    NSUInteger length;
} NSRange;

NS_INLINE NSRange NSMakeRange(NSUInteger loc, NSUInteger len) {
    NSRange r;
    r.location = loc;
    r.length = len;
    return r;
}

If you just want an existing struct with 2 floats and you don't mind including GLKit, you could use GLKVector2. It also has a Make function.

With the introduction of the IOS 9 SDK, a new structure has been added by Apple which best match the OP subject:

UIFloatRange UIFloatRangeMake(CGFloat minimum, CGFloat maximum); // The range of motion for attached objects.

There are couple of useful helper functions to compare ranges too:

BOOL UIFloatRangeIsInfinite(UIFloatRange range);
BOOL UIFloatRangeIsEqualToRange(UIFloatRange range, UIFloatRange otherRange);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!