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

Swift中如何调整iPad端UITabBar中间自定义item的图标与标签居中

UITabBar iPad端布局异常适配方案

问题场景

自定义UITabBar在iPhone端运行正常,标签栏item为垂直栈布局、内容居中。iPad端UITabBar默认切换为水平栈布局,导致中间自定义按钮的图标和文字无法居中对齐,需要仅在iPad端调整中间item的位置,实现和iPhone一致的居中效果。

原有实现代码

import UIKit
import SwiftIcons

class HomeViewController: UITabBarController, UITabBarControllerDelegate {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
        
        let selectedColor   = UIColor(red: 16.0/255.0, green: 78.0/255.0, blue: 91.0/255.0, alpha: 1.0)
        let unselectedColor = UIColor(red: 16.0/255.0, green: 224.0/255.0, blue: 223.0/255.0, alpha: 1.0)

        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: unselectedColor], for: .normal)
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: selectedColor], for: .selected)
        
        let userUnselectedImage: UIImage = UIImage(named: "add_workout_icon")!.withRenderingMode(.alwaysOriginal)
        let userSelectedImage: UIImage = UIImage(named: "add_workout_icon")!.withRenderingMode(.alwaysOriginal)
        
        tabBar.items![2].image = userUnselectedImage
        tabBar.items![2].selectedImage = userSelectedImage
    }
    
}

效果参考

  • iPhone端正常效果:iphone image
  • iPad端异常效果:ipad image

适配方案

方案1:调整内边距(侵入性最低,推荐)

在原有代码的viewDidLoad方法末尾添加如下适配逻辑,仅对iPad端生效,不会影响iPhone原有布局:

if UIDevice.current.userInterfaceIdiom == .pad {
    // 调整图标左偏移量,数值可根据实际布局偏差微调
    tabBar.items![2].imageInsets = UIEdgeInsets(top: 0, left: -12, bottom: 0, right: 12)
    // 同步调整标题偏移量,保证和图标对齐
    tabBar.items![2].titlePositionAdjustment = UIOffset(horizontal: -12, vertical: 0)
}

方案2:强制全局布局样式(iOS14及以上版本支持)

如果希望所有tabBarItem都和iPhone端保持一致的居中排列逻辑,可直接统一UITabBar的item排列规则:

if UIDevice.current.userInterfaceIdiom == .pad {
    tabBar.itemPositioning = .centered
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 15:45:10