You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让无标题的高高度自定义UITabBarItem在所有iPhone上垂直居中?

解决自定义UITabBar在带Home键iPhone上的TabBarItem垂直居中问题

问题原因

你现在的代码只通过sizeThatFits调整了TabBar的整体高度,在带刘海的机型上因为加上了safeAreaInsets.bottom,系统的布局逻辑能适配这个高度变化,所以图标居中正常。但在带Home键的机型上,没有安全区底部 inset,系统默认的TabBar子视图约束还是按照原本的默认高度来布局,导致TabBarItem没法在自定义的高度里垂直居中。

修复方案

我们需要重写layoutSubviews方法,手动调整每个TabBarItem容器的位置,让它们在自定义高度的TabBar里垂直居中。修改后的代码如下:

class CustomUITabBar: UITabBar {
    @IBInspectable private var height: CGFloat = .zero
    
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        guard let window = UIApplication.shared.windows.first else { return super.sizeThatFits(size) }
        var sizeThatFits = super.sizeThatFits(size)
        if #available(iOS 11.0, *) {
            sizeThatFits.height = height + window.safeAreaInsets.bottom
        } else {
            sizeThatFits.height = height
        }
        return sizeThatFits
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 遍历子视图,找到所有TabBarItem对应的UIControl容器
        for subview in subviews {
            guard let tabButton = subview as? UIControl else { continue }
            var buttonFrame = tabButton.frame
            // 计算垂直居中的Y坐标:(TabBar总高度 - 按钮高度) / 2
            buttonFrame.origin.y = (self.bounds.height - buttonFrame.size.height) / 2
            tabButton.frame = buttonFrame
        }
    }
}

额外说明

  • 这里通过UIControl来筛选TabBarItem的容器视图,因为UITabBarButton是UIControl的子类,这个方式在目前的iOS版本里都很稳定。
  • 注意自定义的height不要小于系统默认的TabBar高度(一般是49pt),不然可能会出现图标被截断的情况。
  • 如果担心未来系统内部结构变化,也可以通过KVC获取item对应的视图,但遍历UIControl的方式足够满足大多数场景的需求。

内容的提问来源于stack exchange,提问作者Miki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 20:12:38