Swift自定义iOS中的TabBarController并为其添加动画

2020-01-08 23:07:41于丽
易采站长站为您分析Swift自定义iOS中的TabBarController并为其添加动画的方法,即自定义TabBarController中的的TabBar并为自定义的TabBar增加动画效果,需要的朋友可以参考下  

自定义TabBarController
有时候默认的TabBarController不能满足我们的开发需求,比如你想用彩色的图标,系统却只调用图标的轮廓,所以我们需要自己定义一下TabBar。

方法一:修改TabBarController中的TabBar
新建 CustomTabBarController 类继承自 UITabBarController,并在Storyboard中设置:

Swift,iOS,TabBarController

首先自定义 tabBar 的背景,在 viewDidLoad() 方法中添加:

复制代码
// 用图片
self.tabBar.backgroundImage = UIImage(named: "TabBarBG")
// 或 
// 直接用颜色
self.tabBar.barTintColor = UIColor.blackColor()
然后修改每个子ViewController中的TabBarItem,在 viewDidLoad() 方法中继续添加:
复制代码
for (index, viewController) in self.viewControllers!.enumerate() {
    // 声明 TabBarItem 的Image,如果没有imageWithRenderingMode方法Image只会保留轮廓
    let image = UIImage(named: "TabBar(index)")?.imageWithRenderingMode(.AlwaysOriginal)
    let selectedImage = UIImage(named: "TabBar(index)Sel")?.imageWithRenderingMode(.AlwaysOriginal)

 

    // 声明新的无标题TabBarItem     
    let tabBarItem = UITabBarItem(title: nil, image: image, selectedImage: selectedImage)
    // 设置 tabBarItem 的 imageInsets 可以使图标居中显示
    tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0)

    viewController.tabBarItem = tabBarItem
}


完成!效果如下所示:

 

Swift,iOS,TabBarController