Pages

October 3, 2013

Reverse a NSString chars

How can I reverse a NSString?
Just use this convenient Objective-C method.


/** Reverse all characters of a string.

 @param str String to invert.
 @return Return the reversed string.

 */
+ (NSString *)reverseString:(NSString *)str {
    NSMutableString *reversed = [NSMutableString string];
    NSInteger charIndex = [str length];
    while (charIndex > 0) {
        charIndex--;
        NSRange subRange = NSMakeRange(charIndex, 1);
        [reversed appendString:[str substringWithRange:subRange]];
    }
    return reversed;
}



Download the ready-for-use source file (.m) of Reverse a NSString chars

October 1, 2013

Remap value in another range (eg: percentage or rate)

A simple math problem is remapping a value in another context, like a percentage.
So look to this useful Objective-C method.


/** Returns value remapped in a new range.

 @param oldVal Original float value to be remapped.
 @param oldMaxVal Maximum value of the original range.
 @param oldMinVal Minimum value of the original range.
 @param newMaxVal Maximum value of the new range.
 @param newMinVal Minimum value of the new range.
 @return Returns the float value remapped in the new range.

 */
+ (CGFloat)value:(CGFloat)oldVal inRemappedRangeDefinedByOldMax:(CGFloat)oldMaxVal oldMin:(CGFloat)oldMinVal
          newMax:(CGFloat)newMaxVal newMin:(CGFloat)newMinVal {

    CGFloat realRange    = oldMaxVal - oldMinVal;
    CGFloat newRange    = newMaxVal - newMinVal;
    CGFloat newVal        = (((oldVal - oldMinVal) * newRange) / realRange) + newMinVal;
    return newVal;
}



Download the ready-for-use source file (.m) of Remap value in another range (eg: percentage or rate)

September 28, 2013

Resize any UIView or even UIView subclasses

I made this Objective-C method because I was boring to write the same code for just an easy function like resizing an UIView.


/** Resize a UIView.

 @param obj A UIView or a subclass of UIView.
 @param size Target size.
 @see moveView:toPoint:

 */
+ (void)resizeView:(UIView *)obj toSize:(CGSize)size {
    if (!obj) { return; }
    CGRect r = obj.frame;
    r.size = size;
    obj.frame = r;
}



Download the ready-for-use source file (.m) of Resize any UIView or even UIView subclasses