Pages

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

No comments:

Post a Comment