Is it possible to apply texture to UIToolbar?

I tried to do this:

[toolbar setTint:[UIColor colorWithPatternImage:[UIImage imageNamed:@"thingFromMyBundle.png"]]];

but he just turned black. At first I suggested that you are not allowed to β€œshade” the texture, but recently I saw applications that can do this. Did I miss something?

Thank.

+3
source share
2 answers

Add 2 files to the project, name them UINavigationBar-CustomTexture.hand UINavigationBar-CustomTexture.m, for example, put this in these files:

.h file:

#import <UIKit/UIKit.h>
@interface UINavigationBar (CustomTexture)
@end

.m file:

#import "UINavigationBar-CustomTexture.h"

@interface UIView (CustomTexture)
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx;
@end

@implementation UINavigationBar (CustomTexture)
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    if ([self isMemberOfClass:[UINavigationBar class]]){
        UIImage *image = [UIImage imageNamed:@"myImage.png"];
        CGContextScaleCTM(ctx, 1.0f, -1.0f);
        CGContextDrawImage(ctx, CGRectMake(0, -image.size.height, self.frame.size.width, self.frame.size.height), image.CGImage);
    }else{
        [super drawLayer:layer inContext:ctx];
    }
}
@end

Include the .h file where you create your navigation controller. Make your png file 320x44. Depending on your texture, change the hue of the navigation bar to something like this (so that the buttons on the navigation bar look better):

[self.navigationController.navigationBar setTintColor:[UIColor colorWithHue:0 saturation:0 brightness:0.5f alpha:0.1f]];
+8

:

_titleToolbar= [[UIToolbar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, kDeviceWidth, 34.0f)];
[_titleToolbar setTranslucent:YES];
[_titleToolbar setBackgroundColor:[UIColor clearColor]];

CALayer* backgroundLayer = [CALayer layer];
[backgroundLayer setFrame:CGRectMake(0, 0, kDeviceWidth, _titleToolbar.frame.size.height)];

UIImage* patternImage = [UIImage deviceImageNamed:@"topToolbarBackground"];
[backgroundLayer setBackgroundColor:[UIColor colorWithPatternImage:patternImage].CGColor];
[[_titleToolbar layer] insertSublayer:backgroundLayer atIndex:0];

>

+2

Source: https://habr.com/ru/post/1738594/


All Articles