在ios4.3以上版本,想把UIToolbar的顏色改成灰色,
但是下面的代碼沒有實現:
- (void)drawRect:(CGRect)rect {
UIGraphicsBeginImageContext(rect.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
[[UIColor colorWithRed:64.0f/255.0f
green:64.0f/255.0f
blue:64.0f/255.0f
alpha:1.0f] set];
CGRect myRect = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
CGContextFillRect(ctx, myRect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
CGContextRestoreGState(ctx);
UIGraphicsEndImageContext();
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
為什麼?
可以通過使用灰色的背景圖片實現。用下面代碼加入圖片:
UIToolbar *toolBar = //此處添加toolbar
UIImage *toolbarBkg = [[UIImage imageNamed: @"toolbarBkg.png"] stretchableImageWithLeftCapWidth:0 topCapHeight:0];
if ([toolBar respondsToSelector:@selector(setBackgroundImage:forToolbarPosition:barMetrics:)])
[toolBar setBackgroundImage:toolbarBkg forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
else {
UIImageView *background = [[UIImageView alloc] initWithImage:toolbarBkg];
background.frame = toolBar.frame;
[toolBar insertSubview:background atIndex:0];
}