Swift讓標籤欄按鈕UITabBarItem圖片置中(沒有文字)

來源:互聯網
上載者:User

對於標籤欄(UITabBar),當tabBarItem不需要title只要image的時候,圖片下方也是會佔據一個空間的。
我們可以通過 tabBarItem.imageInsets 來設定位移量,使得image表徵圖置中顯示。
(注意:top和bottom要設定成相反數,不然image的大小會一直改變。)
 

import UIKit
 
class MainTabViewController:UITabBarController
{
    override func viewDidLoad()
    {
        super.viewDidLoad()
        //一共包含了兩個視圖
        let qqView = QQViewController()
        //qqView.title = ""
        let skypeView = SkypeViewController()
        //skypeView.title = ""
        
        //分別聲明兩個視圖控制器
        let qq = UINavigationController(rootViewController:qqView)
        qq.tabBarItem.image = UIImage(named:"qq")
        qq.tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
        
        let skype = UINavigationController(rootViewController:skypeView)
        skype.tabBarItem.image = UIImage(named:"skype")
        skype.tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
        
        self.viewControllers = [qq,skype]
    }
}

UITabBarItem顯示真實自訂的圖片而非顏色填充

讓TabBarItem 顯示出我們設定的圖片的真實樣子,需要看以下設定方法在AppDelegate.h中,拿到所有的item然後統一設定成自訂的圖片分別是選中和未選中,針對ios7以後


_tabBarController = [[UITabBarController alloc]init];
    [_tabBarController setViewControllers:@[recNav,feedNav,postNav,loginNav]];
    // 拿到 TabBar 在拿到想應的item
    UITabBar *tabBar = _tabBarController.tabBar;
    UITabBarItem *item0 = [tabBar.items objectAtIndex:0];
    UITabBarItem *item1 = [tabBar.items objectAtIndex:1];
    UITabBarItem *item2 = [tabBar.items objectAtIndex:2];
    UITabBarItem *item3 = [tabBar.items objectAtIndex:3];
    // 對item設定相應地圖片
    item0.selectedImage = [[UIImage imageNamed:@"recognize-1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];;
    item0.image = [[UIImage imageNamed:@"recognize"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
     
    item1.selectedImage = [[UIImage imageNamed:@"life-1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];;
    item1.image = [[UIImage imageNamed:@"life"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
     
    item2.selectedImage = [[UIImage imageNamed:@"edit-1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];;
    item2.image = [[UIImage imageNamed:@"edit"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
     
    item3.selectedImage = [[UIImage imageNamed:@"setting-1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];;
    item3.image = [[UIImage imageNamed:@"setting"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

通過以上代碼設定就把4個item的圖片設定好了當然也可以分別在對應的controller中進行相應地設定,不過建議統一設定修改起來比較省事,如果需要在item點擊有很炫的動畫或是其他樣式,那就需要高度自訂才能實現

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.