Skip to content

Instantly share code, notes, and snippets.

@calt
Last active October 10, 2024 07:06
Show Gist options
  • Save calt/7ea29a65b440c2aa8a1a to your computer and use it in GitHub Desktop.
Save calt/7ea29a65b440c2aa8a1a to your computer and use it in GitHub Desktop.
UITabBar with custom height in Swift, does not work for iOS 14 or later.
// Does not work on iOS 14.0 or later, keeping the gist just for reference.
extension UITabBar {
override open func sizeThatFits(size: CGSize) -> CGSize {
super.sizeThatFits(size)
var sizeThatFits = super.sizeThatFits(size)
sizeThatFits.height = 71
return sizeThatFits
}
}
@jaroshevskii
Copy link

After testing many ways, this one works best for me:

final class CustomTabBar: UITabBar {
    private let topLineLayer: CALayer = {
        let obj = CALayer()
        obj.backgroundColor = UIColor.appBorder.cgColor
        return obj
    }()
    
    private let tabBarAppearance: UITabBarAppearance = {
        let obj = UITabBarAppearance()
        obj.stackedLayoutAppearance.normal.titleTextAttributes = [
            .font: UIFont.interFont(ofSize: 12.sizeW, weight: .medium),
        ]
        return obj
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setup()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        topLineLayer.frame.size = CGSize(width: bounds.width, height: 1)
    }
    
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        var sizeThatFits = super.sizeThatFits(size)
        sizeThatFits.height = 64 + safeAreaInsets.bottom // 64 is custom height
        return sizeThatFits
    }
}

// MARK: - Setup
extension CustomTabBar {
    private func setup() {
        standardAppearance = tabBarAppearance
        tintColor = .appLabel
        unselectedItemTintColor = .appStroke
        layer.addSublayer(topLineLayer)
    }
}
final class CustomTabBarController: UITabBarController {
    private let customTabBar = CustomTabBar()
    
    override func loadView() {
        super.loadView()
        
        setValue(customTabBar, forKey: "tabBar")
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment