iOS開發之功能模塊--關於自定義TabBar條


只上項目中用到的代碼:

1、實現重寫TabBar的TabBarItem,然后在中間額外加一個按鈕。

1 #import <UIKit/UIKit.h>
2 
3 @interface BikeTabBar : UITabBar
4 
5 @end
 1 #import "BikeTabBar.h"
 2 
 3 @interface BikeTabBar ()
 4 
 5 //@property (nonatomic,weak)UIButton *centerButton;
 6 
 7 @end
 8 
 9 @implementation BikeTabBar
10 
11 
12 
13 - (void)layoutSubviews
14 {
15     [super layoutSubviews];
16     
17     UIButton *centerButton = [UIButton buttonWithType:UIButtonTypeCustom];
18     [centerButton setImage:[UIImage imageNamed:@"tab_bar_ride0"] forState:UIControlStateNormal];
19     [centerButton setImage:[UIImage imageNamed:@"tab_bar_ride1"] forState:UIControlStateHighlighted];
20     // 一定要記得設置尺寸
21     [centerButton sizeToFit];
22     [self addSubview:centerButton];
23     
24     // 獲取子按鈕總數
25     NSInteger count = self.items.count;
26     CGFloat x = 0;
27     CGFloat y = 0;
28     CGFloat w = self.width / (count + 1);
29     CGFloat h = self.height;
30     
31     int i = 0;
32     // 遍歷所有的tabBarButton
33     for (UIControl *tabBarButton in self.subviews) {
34         if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
35             if (i == 2) {
36                 i += 1;
37             }
38             x = i * w;
39             //  設置UITabBarButton位置
40             tabBarButton.frame = CGRectMake(x, y, w, h);
41             tabBarButton.tag = i;
42             
43             i++;
44             
45             // 監聽 UIControlEventTouchDownRepeat : 短時間內連續地重復點擊
46             //            [tabBarButton addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchDownRepeat];
47             [tabBarButton addTarget:self action:@selector(centerButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
48         }
49     }
50     
51     // 設置加號按鈕位置
52     centerButton.center = CGPointMake(UIScreenWidth * 0.5, h * 0.5);
53 }
54 
55 
56 - (void)centerButtonClicked:(UIButton*)sender{
57     
58 }
59 
60 @end

2、實現修改中間的UITabBarItem的樣式,比如大小、位置

這個需求和上面一個需求在用戶交互有一個區別,上面自定義的TabBar中間的按鈕是額外添加的,不具備UITabBarController的UITabBarItem的本質,在用戶交互中,比如選擇了第一個Item,然后再點擊中間這個額外添加的按鈕,那個第一個Item並不會自動切換成未選中的狀態。

而對於這第二個個需求,本人一開始覺得要自定義TabBar,其實根本不需要。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM