您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 自訂 UITabBar 完整實作

編輯:iOS 開發綜合

自訂 UITabBar 常用於替換系統樣式、加入中央加號按鈕,或調整文字與圖示狀態。實作時可建立 UITabBar 子類別,再利用 KVC 取代 UITabBarController 內建的 tabBar。

自訂 TabBar 類別

YYTabBar 繼承 UITabBar,內部加入 plusButton,並在 layoutSubviews 中重新安排所有 UITabBarButton 的位置。

- (void)setupAllTabBarButtonsFrame {
    int index = 0;
    for (UIView *tabBarButton in self.subviews) {
        if (![tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) continue;

        CGFloat buttonW = self.width / (self.items.count + 1);
        CGFloat buttonH = self.height;
        tabBarButton.width = buttonW;
        tabBarButton.height = buttonH;

        if (index >= 2) {
            tabBarButton.x = buttonW * (index + 1);
        } else {
            tabBarButton.x = buttonW * index;
        }
        tabBarButton.y = 0;
        index++;
    }
}

取代系統 TabBar

YYTabBar *customTabBar = [[YYTabBar alloc] init];
[self setValue:customTabBar forKeyPath:@"tabBar"];

這裡不能直接設定 self.tabBar,因為該屬性通常為唯讀,因此使用 KVC 修改內部值。

文字顏色與選中狀態

可透過 tabBarItem 的 titleTextAttributes 設定普通與選中狀態的文字樣式。

NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
textAttrs[UITextAttributeTextColor] = [UIColor blackColor];
textAttrs[UITextAttributeFont] = [UIFont systemFontOfSize:10];
[childVc.tabBarItem setTitleTextAttributes:textAttrs forState:UIControlStateNormal];

NSMutableDictionary *selectedTextAttrs = [NSMutableDictionary dictionary];
selectedTextAttrs[UITextAttributeTextColor] = [UIColor orangeColor];
[childVc.tabBarItem setTitleTextAttributes:selectedTextAttrs forState:UIControlStateSelected];

加號按鈕事件

可透過 delegate 把點擊事件傳回 UITabBarController,再以模態方式顯示發訊息頁面。

-(void)tabBarDidClickedPlusButton:(YYTabBar *)tabBar {
    YYComposeViewController *compose = [[YYComposeViewController alloc] init];
    YYNavigationViewController *nav = [[YYNavigationViewController alloc] initWithRootViewController:compose];
    [self presentViewController:nav animated:YES completion:nil];
}

若使用 iOS 7 以上版本,selectedImage 可加上 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal,避免系統自動渲染成藍色。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved