對於標簽欄(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點擊有很炫的動畫或是其他樣式,那就需要高度自定義才能實現