Могу ли я дать UIToolBar собственный фон в моем приложении для iPhone?
Можно ли дать UIToolBar собственный фон с изображения, а не обычный оттенок синего/черного цвета?
Я попытался дать представление фону и установить непрозрачность UIToolBar, но также влияет на непрозрачность любых UIBarButtons на нем.
Ответы
Ответ 1
Отвечая на мой собственный вопрос здесь!!! Переопределение функции drawRect и создание реализации UIToolbar делает трюк:)
@implementation UIToolbar (CustomImage)
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed: @"nm010400.png"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end
Ответ 2
UIToolbar наследует UIView. Это просто сработало для меня:
[topBar insertSubview:[[[UIImageView alloc] initWithImage:[UIImage imageNamed:BAR_BKG_IMG]] autorelease] atIndex:0];
Ответ 3
Немного измененная версия ответа loreto, которая работает для меня на ios 4 и 5:
// Set the background of a toolbar
+(void)setToolbarBack:(NSString*)bgFilename toolbar:(UIToolbar*)toolbar {
// Add Custom Toolbar
UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:bgFilename]];
iv.frame = CGRectMake(0, 0, toolbar.frame.size.width, toolbar.frame.size.height);
iv.autoresizingMask = UIViewAutoresizingFlexibleWidth;
// Add the tab bar controller view to the window and display.
if([[[UIDevice currentDevice] systemVersion] intValue] >= 5)
[toolbar insertSubview:iv atIndex:1]; // iOS5 atIndex:1
else
[toolbar insertSubview:iv atIndex:0]; // iOS4 atIndex:0
toolbar.backgroundColor = [UIColor clearColor];
}
Ответ 4
Это подход, который я использую для совместимости с iOS 4 и 5:
if ([toolbar respondsToSelector:@selector(setBackgroundImage:forToolbarPosition:barMetrics:)]) {
[toolbar setBackgroundImage:[UIImage imageNamed:@"toolbar-background"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
} else {
[toolbar insertSubview:[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"toolbar-background"]] autorelease] atIndex:0];
}
Ответ 5
просто добавьте этот фрагмент в свой -(void)viewDidLoad{}
[toolBarName setBackgroundImage:[UIImage imageNamed:@"imageName.png"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
Ответ 6
Если вы используете ответ idimmu и хотите, чтобы ваши barbuttonitems были цветными, а не по умолчанию, вы можете добавить эти пару строк кода в свою категорию:
UIColor *color = [UIColor redColor];
self.tintColor = color;
Ответ 7
Вы можете использовать API Appearance с iOS5:
[[UIToolbar appearance] setBackgroundImage:[UIImage imageNamed:@"navbar_bg"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
Ответ 8
Чтобы быть совместимым с iOS 5, вы можете сделать что-то вроде этого
-(void) addCustomToolbar {
// Add Custom Toolbar
UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"customToolbar.png"]];
img.frame = CGRectMake(-2, -20, img.frame.size.width+4, img.frame.size.height);
// Add the tab bar controller view to the window and display.
if( SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO( @"5.0" ) )
[self.tabBarController.tabBar insertSubview:img atIndex:1]; // iOS5 atIndex:1
else
[self.tabBarController.tabBar insertSubview:img atIndex:0]; // iOS4 atIndex:0
self.tabBarController.tabBar.backgroundColor = [UIColor clearColor];
// Override point for customization after application launch.
[self.window addSubview:tabBarController.view];
}
Ответ 9
эта работа отлично подходит для меня:
ToolbarOptions *tbar = [[ToolbarOptions alloc] init];
[tbar setToolbarBack:@"footer_bg.png" toolbar:self.toolbarForPicker];
[tbar release];
#import <Foundation/Foundation.h>
@interface ToolbarOptions : NSObject {
}
-(void)setToolbarBack:(NSString*)bgFilename toolbar:(UIToolbar*)toolbar;
@end
#import "ToolbarOptions.h"
@implementation ToolbarOptions
-(void)setToolbarBack:(NSString*)bgFilename toolbar:(UIToolbar*)bottombar {
// Add Custom Toolbar
UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:bgFilename]];
iv.frame = CGRectMake(0, 0, bottombar.frame.size.width, bottombar.frame.size.height);
iv.autoresizingMask = UIViewAutoresizingFlexibleWidth;
// Add the tab bar controller view to the window and display.
if([[[UIDevice currentDevice] systemVersion] intValue] >= 5)
[bottombar insertSubview:iv atIndex:1]; // iOS5 atIndex:1
else
[bottombar insertSubview:iv atIndex:0]; // iOS4 atIndex:0
bottombar.backgroundColor = [UIColor clearColor];
}
@end
Ответ 10
Вы можете сделать это с категорией, которая в основном добавляет новое свойство в UIToolBar. Переопределение drawRect
может работать, но это не обязательно будущее доказательство. Та же стратегия для пользовательского UINavigationBar
перестала работать с iOS 6.
Вот как я это делаю.
.h файл
@interface UIToolbar (CustomToolbar)
@property (nonatomic, strong) UIView *customBackgroundView;
@end
.m file
#import "CustomToolbar.h"
#import
static char TIToolbarCustomBackgroundImage;
@implementation UIToolbar (CustomToolbar)
- (void)setCustomBackgroundView:(UIView *)newView {
UIView *oldBackgroundView = [self customBackgroundView];
[oldBackgroundView removeFromSuperview];
[self willChangeValueForKey:@"tfCustomBackgroundView"];
objc_setAssociatedObject(self, &TIToolbarCustomBackgroundImage,
newView,
OBJC_ASSOCIATION_RETAIN);
[self didChangeValueForKey:@"tfCustomBackgroundView"];
if (newView != nil) {
[self addSubview:newView];
}
}
- (UIView *)customBackgroundView {
UIView *customBackgroundView = objc_getAssociatedObject(self, &TIToolbarCustomBackgroundImage);
return customBackgroundView;
}
@end
В вашем коде контроллера контроллера, например. viewDidLoad
if (self.navigationController.toolbar.customBackgroundView == nil) {
self.navigationController.toolbar.customBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigation_bar_background.png"]];
self.navigationController.toolbar.customBackgroundView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
}