今天需要創建一個透明的UIToolbar,便看了下SDK,使用下面代碼
- CGRect barFrame = CGRectMake(900, 0, 124, 40);
- UIToolbar *tb;
- tb = [[UIToolbar alloc]initWithFrame:barFrame];
- tb.barStyle =UIBarStyleDefault;
- tb.tintColor = [UIColor clearColor];
- tb.translucent = YES;
效果如下圖
在邊緣的位置們依然能看出視圖層之間的層疊,所以查看了些資料,原來正確的方法是子類化UIToolbar,設置其backgroundColor
- @interface TranslucentToolbar : UIToolbar
-
- @end
- @implementation TranslucentToolbar
-
- - (void)drawRect:(CGRect)rect {
- // do nothing
- }
-
- - (id)initWithFrame:(CGRect)aRect {
- if ((self = [super initWithFrame:aRect])) {
- self.opaque = NO;
- self.backgroundColor = [UIColor clearColor];
- self.clearsContextBeforeDrawing = YES;
- }
- return self;
- }
- @end
在需要創建的地方使用子類化的UIToolbar
- TranslucentToolbar *tb;
- tb = [[TranslucentToolbar alloc]initWithFrame:barFrame];
效果如下,得到了一個透明的UIToolbar