Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save trantorGurjitSingh/902d986a18c36e27dc92f14c1e3aca50 to your computer and use it in GitHub Desktop.
Save trantorGurjitSingh/902d986a18c36e27dc92f14c1e3aca50 to your computer and use it in GitHub Desktop.
Add Indicator View over tab bar item. (Swift 5)
//
// TabBarIndicatorView.swift
//
// Created by Egzon Pllana on 11/15/20.
// Copyright © 2020 Native Coders. All rights reserved.
//
import UIKit
class TabBarIndicatorView: UIView {
// MARK: - Properties
weak var tabBarController: UITabBarController! // Avoid retain memory cycles
var animationDuration: Double!
var spacing: CGFloat!
// MARK: - Required Init
init(atTabBarController tabBarController: UITabBarController,
withItemHeight itemHeight: CGFloat = 1.5,
withTabColor tabColor: UIColor = .black,
withSpacing spacing: CGFloat = 4,
withAnimationDuration animationDuration: Double = 0.20) {
guard let tabView = tabBarController.tabBar.items?[0].value(forKey: "view") as? UIView else {
super.init(frame: CGRect.zero)
return
}
self.tabBarController = tabBarController
self.animationDuration = animationDuration
self.spacing = spacing
// Setup View Frame
super.init(frame: CGRect(x: tabView.frame.minX+spacing/2,
y: tabBarController.tabBar.frame.minY+0.1,
width: tabView.frame.size.width-spacing,
height: itemHeight))
// SetupUI
self.backgroundColor = tabColor
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Methods
func selectIndex(_ index: Int) {
UIView.animate(withDuration: animationDuration) { [self] in
guard let tabView = tabBarController.tabBar.items?[index].value(forKey: "view") as? UIView else {
return
}
self.frame = CGRect(x: tabView.frame.minX+spacing/2,
y: tabBarController.tabBar.frame.minY+0.1,
width: tabView.frame.size.width-spacing,
height: self.frame.size.height)
}
}
}
// How to use
class TabBarViewController: UITabBarController {
// MARK: - Properties
var indicatorView: TabBarIndicatorView!
// MARK: - View life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Customize Tab Bar
DispatchQueue.main.async {
self.customizeTabBarUI()
}
// Do any additional setup after loading the view.
}
}
extension TabBarViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
// Update indicator view
indicatorView.selectIndex(self.selectedIndex)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment