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

Swift中如何增大TabBar Item标题底部偏移量及所有项底部间距?

调整TabBar Item标题底部偏移 & 增加整体底部间距的实现方案

嘿,这个需求我在项目里碰过好几次,给你两种实用的实现方案,按需选择:

一、单独增大TabBar Item标题的底部偏移量

如果只是想让标题往下(或往上)挪,不需要动图标位置,直接用UITabBarItem的titlePositionAdjustment属性就可以搞定,非常简单:

实现步骤:

  1. 在配置TabBarItem的时候,直接设置偏移量:

    // 创建一个TabBarItem
    let tabItem = UITabBarItem(
        title: "首页",
        image: UIImage(systemName: "house"),
        selectedImage: UIImage(systemName: "house.fill")
    )
    // 设置标题偏移:horizontal是左右偏移,vertical是上下偏移(正数=向下移,负数=向上移)
    tabItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: 8)
    
  2. 如果要给所有TabBarItem统一设置,可以遍历TabBar的items数组:

    override func viewDidLoad() {
        super.viewDidLoad()
        
        tabBar.items?.forEach { item in
            item.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: 8)
        }
    }
    

这个方法的好处是不用自定义控件,系统原生支持,适配性拉满。


二、给所有TabBarItem增加整体底部间距

如果是想让整个Item(图标+标题)和TabBar底部之间留出更多空白,就得自定义UITabBar来调整内部布局了:

实现步骤:

  1. 创建自定义UITabBar类,重写layoutSubviews方法调整子视图位置:

    class CustomTabBar: UITabBar {
        // 自定义底部间距,按需修改数值
        private let bottomSpacing: CGFloat = 10
        
        override func layoutSubviews() {
            super.layoutSubviews()
            
            // 遍历TabBar里的所有按钮(UITabBarButton是私有类,用UIControl筛选)
            subviews.forEach { subview in
                guard subview is UIControl else { return }
                
                // 把按钮往上移动bottomSpacing的距离,同时缩小按钮高度(避免超出TabBar范围)
                subview.frame = CGRect(
                    x: subview.frame.origin.x,
                    y: subview.frame.origin.y - bottomSpacing,
                    width: subview.frame.size.width,
                    height: subview.frame.size.height - bottomSpacing
                )
            }
            
            // 可选:如果需要保持TabBar背景的完整显示,可以调整背景视图的位置
            backgroundView?.frame = bounds
        }
    }
    
  2. 在TabBarController中使用自定义TabBar:

    • 代码方式:
      class MainTabBarController: UITabBarController {
          override func viewDidLoad() {
              super.viewDidLoad()
              // 替换系统TabBar为自定义的
              tabBar = CustomTabBar()
          }
      }
      
    • Storyboard方式:选中TabBar,在Identity Inspector里把Class改成CustomTabBar即可。

注意事项:

  • 因为UITabBarButton是系统私有类,所以用UIControl来筛选子视图,避免不同iOS版本的兼容性问题;
  • 如果你的TabBar有自定义背景或阴影,记得在layoutSubviews里同步调整相关视图的布局,避免显示异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:03:37