首页 > 解决方案 > 无法在 iPad 上对齐 TabBar 项目

问题描述

TabBar 项目(图像和标题)在所有 iPhone 上完全自动对齐,但在 iPad 上看起来非常难看(见下图):

IM1

我已经尝试过了,在 Stackoverflow 上的另一个类似问题上找到了这个,但没有帮助我:

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    UITabBar.appearance().itemPositioning = .fill //also tried .center
}

也许原因是我的 TabBar 设置中的另一行,我没有成功找出哪一行:

viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
        
    setupTabBarItems()
    setupTabBarUI()
}

viewDidLayout 子视图:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
            
    tabBar.frame.size.height = tabBarBarHeight
    tabBar.frame.origin.y = view.frame.height - tabBarBarHeight
}

设置方法:

func setupTabBarItems() {
    let titleAttributes: [NSAttributedString.Key: AnyObject] = [NSAttributedString.Key.font:UIFont.Avenir(.roman, size: 22)]
        
let firstSelectionViewController = FirstSelectionViewController()
firstSelectionViewController.tabBarItem = UITabBarItem(title: "kFirst".localized(), image: UIImage(named: "first"), selectedImage: UIImage(named: "firstSelected"))
        firstSelectionViewController.tabBarItem.setTitleTextAttributes(titleAttributes, for: .normal)
        
let secondSelectionViewController = SecondSelectionViewController()
secondSelectionViewController.tabBarItem = UITabBarItem(title: "kSecond".localized(), image: UIImage(named: "second"), selectedImage: UIImage(named: "secondSelected"))
        secondSelectionViewController.tabBarItem.setTitleTextAttributes(titleAttributes, for: .normal)
        
        
        
let tabBarList = [firstSelectionViewController, secondSelectionViewController]
viewControllers = tabBarList
}

func setupTabBarUI() {
UITabBar.appearance().tintColor = UIColor.white
        
self.tabBar.layer.masksToBounds = true
self.tabBar.barStyle = UIBarStyle.black
self.tabBar.layer.cornerRadius = 20
if #available(iOS 11.0, *) {
            self.tabBar.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        } else {
 }
        
tabBar.barTintColor = UIColor.mainDarkBlue
UITabBar.appearance().isTranslucent = false
let numberOfItems = CGFloat(tabBar.items!.count)
let tabBarItemSize = CGSize(width: self.view.frame.width / numberOfItems, height: tabBarBarHeight)
        tabBar.selectionIndicatorImage = UIImage.imageWithColor(color: UIColor.mainDarkBlueTransparent, size: 100).resizableImage(withCapInsets: UIEdgeInsets.zero)
        
// remove default border
tabBar.frame.size.width = self.view.frame.width + 4
tabBar.frame.origin.x = -2
}

标签: swiftuitabbarcontrolleruitabbartabbar

解决方案


推荐阅读