我可以在我的iPhone应用程序中为UIToolBar提供自定义背景吗?

Rus*_*hes 25 iphone uitoolbar

是否可以从图像中为UIToolBar提供自定义背景而不是通常的有色蓝/黑淡出?

我已尝试为视图提供背景并设置UIToolBar的不透明度,但这也会影响其上任何UIBarButtons的不透明度.

Rus*_*hes 40

在这里回答我自己的问题!覆盖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
Run Code Online (Sandbox Code Playgroud)

  • 您正在UIToolbar上创建"类别". (14认同)
  • 这工作表示感谢,但我认为最好将UIToolbar子类化. (9认同)
  • 简单地说'drawInRect:self.bounds`怎么样? (6认同)

Aja*_*tam 16

UIToolbar继承自UIView.这对我有用:

[topBar insertSubview:[[[UIImageView alloc] initWithImage:[UIImage imageNamed:BAR_BKG_IMG]] autorelease] atIndex:0];
Run Code Online (Sandbox Code Playgroud)


Chr*_*ris 10

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's 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];
}
Run Code Online (Sandbox Code Playgroud)

  • 在iOS 5中,有新的API允许自定义控件.无需插入子视图.此外,检查系统版本不是推荐的做法,respondsToSelector是一个更强大的替代方案. (2认同)

Chr*_*lay 9

这是我用于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];
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*eus 7

只需将此片添加到您的 -(void)viewDidLoad{}

[toolBarName setBackgroundImage:[UIImage imageNamed:@"imageName.png"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
Run Code Online (Sandbox Code Playgroud)