做TabbarController简单封装,并添加点击动画效果
import UIKit
class HPTabbarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self // 指定代理 --> extension实现代理方法
self.view.backgroundColor = UIColor.white
let tabBar = UITabBar.appearance()
tabBar.tintColor = UIColor(red: 245 / 255, green: 90 / 255, blue: 93 / 255, alpha: 1/0)
self.addChildViewControllers()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func addChildViewControllers() { // 如果使用文字和切图放在一起的话
addChildViewController(childController: HomeViewController(), title: "首页", imageName: "homeUnselected", selectedImage: "homeSelected")
addChildViewController(childController: VideoViewController(), title: "视频", imageName: "videoUnselected", selectedImage: "videoSelected")
addChildViewController(childController: MineViewController(), title: "我", imageName: "mineUnselected", selectedImage: "mineSelected")
}
private func addChildViewController(childController: UIViewController, title:String, imageName: String, selectedImage: String) {
childController.tabBarItem.image = UIImage(named: imageName)
childController.tabBarItem.selectedImage = UIImage(named:selectedImage)
childController.title = title
// childController.tabBarItem.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0) // 如果文字和UI切图在一起 就将title设置为空字符串
let navController = HPNavigationController(rootViewController: childController)
addChildViewController(navController)
}
}
extension HPTabbarController : UITabBarControllerDelegate {
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
if let index = tabBar.items?.index(of: item) {
tabbarButtonClick(index: index)
// 发送通知用来监听tabbar点击事件
// NotificationCenter.default.post(name: NSNotification.Name(rawValue: "TabBarDidSelect"), object: self, userInfo: ["info": index])
}
}
func tabbarButtonClick(index: Int) {
var arr = [UIView]()
for tabBarButton in tabBar.subviews {
if tabBarButton.isKind(of: NSClassFromString("UITabBarButton")!) {
arr.append(tabBarButton)
}
}
let animation = CABasicAnimation(keyPath: "transform.scale")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) // 速度控制函数
animation.duration = 0.15
animation.fromValue = NSNumber(value: 0.7)
animation.toValue = NSNumber(value: 1.2)
arr[index].layer.add(animation, forKey: nil)
}
}