Pages

Showing posts with label uiview. Show all posts
Showing posts with label uiview. Show all posts

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

 

September 25, 2013

Get the maximum available width (or height) for items in a box

I have a UIView container and some items with fixed size.
What's the maximum allowed space betweem them?


/** Returns the maximum space between items so that they could stay within a container.

 @param numItems Number of items that must stay within a given container.
 @param itemDimenions Size of single item.
 @param containerDim Size of container.
 @return Returns the dimension of the space between all items.
 @see maxNumberOfItemsWithDimension:minSpacer:inContainerOfDimension:

 */
+ (CGFloat)maxSpaceBetweenItems:(NSInteger)numItems withDimension:(CGFloat)itemDimenions inContainerOfDimension:(CGFloat)containerDim {
    return (containerDim - numItems * itemDimenions) / (numItems + 1);
}



Download the ready-for-use source file (.m) of Get the maximum available width (or height) for items in a box

September 24, 2013

Get the maximum available items that could stay in a box

I have a UIView container and I need to put some items with fixed size in t.
How many objects can I have?


/** Returns the maximum number of items that could stay within a container.

 It takes into account also a minimum spacer between items.

 @param itemDimension Size of single item.
 @param itemMinSpacer Minimum space between items.
 @param containerDim Size of container.
 @return Returns the number of maximum items that can fit into the container.
 @see maxSpaceBetweenItems:withDimension:inContainerOfDimension:

 */
+ (NSInteger)maxNumberOfItemsWithDimension:(CGFloat)itemDimension minSpacer:(CGFloat)itemMinSpacer inContainerOfDimension:(CGFloat)containerDim {
    CGFloat num = (containerDim - itemMinSpacer) / (itemMinSpacer + itemDimension);
    return floorf(num);
}


Download the ready-for-use source file (.m) of Get the maximum available items that could stay in a box

September 14, 2013

Show or Hide all UIView subviews with a single function

While using Cocoa framework I often need to show or hide all child subviews of a parent UIView in a nutshell.
Use this Objective-C method in your Xcode projects!


/** Shows or hides all subviews of a View.

 @param hide Boolean value that defines hide (true) or show (false).
 @param ownerMainView A UIView or a subclass of UIView.
 @see showAllSubviewsOf:
 @see hideAllSubviewsOf:
 @see removeAllSubviewsOfClass:fromView:
 @see getAllSubviewsOfClass:fromView:

 */
+ (void)hide:(BOOL)hide allSubviewsOf:(UIView *)ownerMainView {
    if (!ownerMainView) { return; }
    for (NSInteger i=0; i<[ownerMainView.subviews count]; i++) {
        [[ownerMainView.subviews objectAtIndex:i] setHidden:hide];
    }
}



Download the ready-for-use source file (.m) of Show or Hide all UIView subviews with a single function

September 2, 2013

Crossfade NSString text inside a UILabel or UITextField

One of my favourite effect is the so-called crossfade effect.
Well, I made a crossfade animation between two NSStrings in a UIView (actually UILabel or UITextField).


/** Crossfade effect for text.

 @param view A UILabel or UITextField that contains the old text.
 @param text New string to show.
 @param duration Animation duration in milliseconds.
 @return Returns true on success, false otherwise.

 */
+ (BOOL)crossFadeCurrentTextInView:(UIView *)view withNewText:(NSString *)text duration:(CGFloat)duration {
    if (!view) { return NO; }
    // Works only for UILabel or UITextField.
    if ([view isKindOfClass:[UILabel class]] || [view isKindOfClass:[UITextField class]]) {
        CATransition *animation = [CATransition animation];
        animation.duration        = duration;
        animation.type            = kCATransitionFade;
        animation.timingFunction= [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        [view.layer addAnimation:animation forKey:@"changeTextTransition"];

        if ([view isKindOfClass:[UILabel class]]) {
            ((UILabel *)view).text = text;
        } else {
            ((UITextField *)view).text = text;
        }

        [view.layer performSelector:@selector(removeAnimationForKey:) withObject:@"changeTextTransition" afterDelay:duration]; // Remove animation.
        return YES;
    }
    return NO;
}



Download the ready-for-use source file (.m) of Crossfade NSString text inside a UILabel or UITextField

August 23, 2013

How to round corners of UIView

Every default UIButton or even UIView have a great look! You see, that amazing effect of the rounding corner...
Ok, not so difficult to achieve, but while bother if you can use this useful function?


/** Round corners of a View with a radius.

 @param view A UIView or a subclass of UIView.
 @param radius Length of radius.
 @see roundCornersForView:

 */
+ (void)roundCornersForView:(UIView *)view withRadius:(CGFloat)radius {
    if (!view) { return; }
    view.layer.cornerRadius        = radius;
    view.layer.masksToBounds    = YES;
    view.layer.borderWidth        = 1.0f;
}



Download the ready-for-use source file (.m) of How to round corners of UIView

August 16, 2013

Remove all UIView subviews filtered by a Class

How can I remove all child subviews of a certain class type from a parent UIView?
You can use my useful function.


/** Remove all subviews of a type from container View.

 @param class Type of subviews to remove.
 @param ownerMainView UIView container.
 @see showAllSubviewsOf:
 @see hideAllSubviewsOf:
 @see getAllSubviewsOfClass:fromView:

 */
+ (void)removeAllSubviewsOfClass:(Class)class fromView:(UIView *)ownerMainView {
    if (!ownerMainView) { return; }
    for (NSInteger i=[ownerMainView.subviews count] - 1; i>=0; i--) {
        if ([[ownerMainView.subviews objectAtIndex:i] isKindOfClass:class]) {
            [[ownerMainView.subviews objectAtIndex:i] removeFromSuperview];
        }
    }
}



Download the ready-for-use source file (.m) of Remove all UIView subviews filtered by a Class

July 27, 2013

Get all child UIView subviews

Do you need a way of getting all the child subviews of a parent UIView? This is my useful function:


/** Get all subviews of a type from container View.

 @param class Type of subviews to remove.
 @param ownerMainView UIView container.
 @return Returns an array of matched child subviews.
 @see showAllSubviewsOf:
 @see hideAllSubviewsOf:
 @see removeAllSubviewsOfClass:fromView:

 */
+ (NSArray *)getAllSubviewsOfClass:(Class)class fromView:(UIView *)ownerMainView {
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    for (id obj in ownerMainView.subviews) {
        if ([obj isKindOfClass:class]) {
            [arr addObject:obj];
        }
    }
    return [NSArray arrayWithArray:arr];
}



Download the ready-for-use source file (.m) of Get all child UIView subviews

July 25, 2013

Move UIView to a new Point

It simply moves a UIView to a new location.
You need:
- http://objective-c-functions.blogspot.com/2013/07/move-uiview-to-new-location-with-offset.html


/** Moves a UIView origin to a new point.

 Please note that the anchor point is the origin (usually the top-left corner).

 @param obj A UIView or a subclass of UIView.
 @param coord Target point.
 @see moveView:toPoint:withOffsetFromOrigin:
 @see resizeView:toSize:

 */
+ (void)moveView:(UIView *)obj toPoint:(CGPoint)coord {
    [LMFunctions moveView:obj toPoint:coord withOffsetFromOrigin:CGPointZero];
}



Download the ready-for-use source file (.m) of Move UIView to a new Point

July 24, 2013

Move UIView to a new location (with offset from origin)

Simple but powerful and useful Objective-C method that moves around a UIView.
I always use it because of no-rewriting of the same code again and again and again.


/** Moves a UIView origin to a new point taking into accout an offset from origin.

 It's especially useful for dragging a View while binding it under a finger.
 Please note that the anchor point is the origin (usually the top-left corner).

 @param obj A UIView or a subclass of UIView.
 @param coord Target point.
 @param offsetFromOrigin Offset X and Y from actual origin.
 @see moveView:toPoint:
 @see resizeView:toSize:

 */
+ (void)moveView:(UIView *)obj toPoint:(CGPoint)coord withOffsetFromOrigin:(CGPoint)offsetFromOrigin {
    if (!obj) { return; }
    CGPoint newCoord = CGPointMake(coord.x + offsetFromOrigin.x, coord.y + offsetFromOrigin.y);
    CGRect r = obj.frame;
    r.origin = newCoord;
    obj.frame = r;
}



Download the ready-for-use source file (.m) of Move UIView to a new location (with offset from origin)

June 22, 2013

UIView that looks like UIBarButton

In an iPhone project I did time ago, I came across the ugly style of the UIView putted in a UIToolbar.
So I digged on the web and found a useful method to apply the fashionable UIBarButtonStyle to a custom UIView.



/** Apply the UIBarButton style to a View.

 @param view A UIView or a subclass of UIView.

 */
+ (void)applyUIBarButtonStyleToView:(UIView *)view {

    if (!view) { return; }

    UIView *_innerView = [[UIView alloc] initWithFrame:view.bounds];
    [_innerView setUserInteractionEnabled:false];

    if ([[view subviews] count] > 0) {
        [view insertSubview:_innerView belowSubview:[[view subviews] objectAtIndex:0]];
    } else {
        [view addSubview:_innerView];
    }

    // Remember these layers so we don't have to call the views to get them repeatedly.
    CALayer* self_layer = [view layer];
    CALayer* inner_layer = [_innerView layer];

    // Create gradient layer.
    CAGradientLayer *_gradientLayer = [CAGradientLayer layer];
    [_gradientLayer setAnchorPoint:CGPointMake(0, 0)];
    // Add one to account for oddities when using CoolButtons in UIToolbar.
    [_gradientLayer setBounds:CGRectMake(0, 0, view.bounds.size.width, (view.bounds.size.height/2.0) + 1)];
    [_gradientLayer setColors:[NSArray arrayWithObjects:
                               (id)[[UIColor colorWithWhite:1.0 alpha:0.3] CGColor],
                               (id)[[UIColor colorWithWhite:1.0 alpha:0.10] CGColor], nil]];
    [inner_layer insertSublayer:_gradientLayer atIndex:1];

    // Create inner glow layer.
    CAGradientLayer *_innerGlowLayer = [CAGradientLayer layer];
    [_innerGlowLayer setAnchorPoint:CGPointMake(0, 0)];
    [_innerGlowLayer setBounds:[view bounds]];
    [_innerGlowLayer setColors:[NSArray arrayWithObjects:
                                (id)[[UIColor colorWithWhite:0.0 alpha:0.60] CGColor],
                                (id)[[UIColor clearColor] CGColor], nil]];
    [inner_layer insertSublayer:_innerGlowLayer atIndex:2];

    // Create inner shadow layer - using a border for now as a hack.
    [inner_layer setBorderWidth:0.7];
    [inner_layer setBorderColor:[[UIColor colorWithWhite:0.0 alpha:0.3] CGColor]];
    [inner_layer setCornerRadius:5.0];
    [inner_layer setMasksToBounds:YES];

    // Add a drop shadow to the layer.
    [self_layer setShadowOffset:CGSizeMake(0, 0.7)];
    [self_layer setShadowColor:[[UIColor whiteColor] CGColor]];
    [self_layer setShadowOpacity:0.5];
    [self_layer setShadowRadius:0.5];
    [self_layer setCornerRadius:5.0];
}




Download the ready-for-use source file (.m) of UIView that looks like UIBarButton

June 21, 2013

Title and subtitle in the UINavigation Bar (AKA title in two lines)

UINavigationController default bar title sucks. Come on, we all, at least one time, need the possibility to write two lines! One for the title and another one for the subtitle.
This is my Objective-C method.


/** Create a View for displaying a title and a subtitle to replace the default UINavigationController title.

 You should manually set the UINavigationController title (navigationItem.title = title;) so that others ViewControllers would see that title instead of "Back" when needed.

 @param title String representing the title.
 @param subtitle String representing the subtitle.
 @return Returns the UIView containing title and subtitle.

 */
+ (UIView *)createNavigationTitleViewWithTitle:(NSString *)title andSubtitle:(NSString *)subtitle {

    if (subtitle == nil) {
        subtitle = @"";
    }

    const NSInteger leftOffset = 15;

    // Replace titleView.
    UIView *headerTitleSubtitleView                = [[UILabel alloc] initWithFrame:CGRectMake(leftOffset, 0, 200, 44)];
    headerTitleSubtitleView.backgroundColor        = [UIColor clearColor];
    headerTitleSubtitleView.autoresizesSubviews    = YES;

    CGRect frame = [subtitle isEqualToString:@""] ? CGRectMake(leftOffset, 0, 160, 44) : CGRectMake(leftOffset, 2, 160, 24);
    UILabel *titleView    = [[UILabel alloc] initWithFrame:frame];
    titleView.backgroundColor            = [UIColor clearColor];
    titleView.font                        = [UIFont boldSystemFontOfSize:19];
    titleView.textAlignment                = NSTextAlignmentCenter;
    titleView.textColor                    = [UIColor whiteColor];
    titleView.shadowColor                = [UIColor darkGrayColor];
    titleView.shadowOffset                = CGSizeMake(0, -1);
    titleView.text                        = title;
    titleView.adjustsFontSizeToFitWidth    = YES;
    titleView.minimumScaleFactor        = 0;
    titleView.lineBreakMode                = NSLineBreakByTruncatingMiddle;
    [headerTitleSubtitleView addSubview:titleView];

    // If subtitle is not empty...
    if (![subtitle isEqualToString:@""]) {
        UILabel *subtitleView = [[UILabel alloc] initWithFrame:CGRectMake(leftOffset, 24, 160, 44-24)];
        subtitleView.backgroundColor            = [UIColor clearColor];
        subtitleView.font                        = [UIFont boldSystemFontOfSize:13];
        subtitleView.textAlignment                = NSTextAlignmentCenter;
        subtitleView.textColor                    = [UIColor whiteColor];
        subtitleView.shadowColor                = [UIColor darkGrayColor];
        subtitleView.shadowOffset                = CGSizeMake(0, -1);
        subtitleView.text                        = subtitle;
        subtitleView.adjustsFontSizeToFitWidth    = YES;
        subtitleView.minimumScaleFactor            = 4;
        subtitleView.lineBreakMode                = NSLineBreakByTruncatingMiddle;
        [headerTitleSubtitleView addSubview:subtitleView];
    }

    return headerTitleSubtitleView;
}



Download the ready-for-use source file (.m) of Title and subtitle in the UINavigation Bar (AKA title in two lines)

June 19, 2013

Flip UIButton title and image

Let's say we have a UIButton which can assume two state. With this convenient function we can do a flip animation between two images and two titles.


/** Flip animation for title and image of a button.

 The button action does not change. This function changes only the title and the image associated to the button.

 @param baseBtn Shared button.
 @param baseView A container View. It only serves for animation effect.
 @param title1 String of the first title.
 @param img1 First image.
 @param title2 String of the second title.
 @param img2 Second image.
 @return Returns true on success, false otherwise.

 */
+ (BOOL)flipButton:(UIButton *)baseBtn ofView:(UIView *)baseView
        withTitle1:(NSString *)title1 img1:(UIImage *)img1
        withTitle2:(NSString *)title2 img2:(UIImage *)img2 {

    NSString *newTitle;
    UIImage *newImage;
    UIViewAnimationTransition flip;

    if ([baseBtn.currentTitle isEqualToString:title1]) {
        newTitle = title2;
        newImage = img2;
        flip = UIViewAnimationTransitionFlipFromRight;
    } else if ([baseBtn.currentTitle isEqualToString:title2]) {
        newTitle = title1;
        newImage = img1;
        flip = UIViewAnimationTransitionFlipFromLeft;
    } else {
        LogError(@"No button found with title: '%@' or '%@'", title1, title2);
        return NO;
    }

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration: 0.50f];
    [UIView setAnimationTransition:flip forView:baseView cache:YES];

    [baseBtn setTitle:newTitle forState:UIControlStateNormal];
    [baseBtn setImage:newImage forState:UIControlStateNormal];

    [UIView commitAnimations];

    return YES;
}



Download the ready-for-use source file (.m) of Flip UIButton title and image