TabBarItem插入会导致单击时出现怪异的徽章行为

时间:2019-01-08 13:27:20

标签: ios swift uitabbarcontroller

我有一个UITabBarController,上面套了一些插图,因此可以并排放置图标和标题

    navController.tabBarItem.title = title.rawValue
    navController.tabBarItem.image = image.resize(width: 30, height: 30).withRenderingMode(.alwaysTemplate)

但是,当单击选项卡时,我的徽章正在向右移动或随机移动。

enter image description here

单击文档后,徽章会明显地向右移动并且不可见。

enter image description here

如果我移除了插图,徽章的行为将达到预期的效果,但是,当然,我无法按照要求使用布局。

import UIKit

enum TabBarItem: String {
    case questions = "Questions"
    case documents = "Documents"
    case profile = "Profile"
}

class MainTabBarController: UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()

        view.hasBackgroundGradient()
        setupTabBar()

        viewControllers = [
            generateNavigationController(for: ChatController(), title: .questions, image: #imageLiteral(resourceName: "bot_icon"), hideNavbar: true),
            generateNavigationController(for: DocumentsController(), title: .documents, image: #imageLiteral(resourceName: "document_icon"), hideNavbar: true),
            generateNavigationController(for: ProfileController(), title: .profile, image: #imageLiteral(resourceName: "profile_icon"))
        ]
    }
}

extension MainTabBarController {
    fileprivate func setupTabBar() {
        tabBar.barTintColor = .white
        tabBar.isTranslucent = false
        tabBar.unselectedItemTintColor = .black
        tabBar.tintColor = UIColor.usingHex("1fb3b7")
    }

    fileprivate func generateNavigationController(for rootViewController: UIViewController, title: TabBarItem, image: UIImage, hideNavbar: Bool = false) -> UIViewController {
        let navController = UINavigationController(rootViewController: rootViewController)
        navController.isNavigationBarHidden = hideNavbar

        if !hideNavbar {
            navController.navigationBar.barTintColor = .white
            navController.navigationBar.isTranslucent = false
        }

        navController.tabBarItem.titlePositionAdjustment = UIOffset(horizontal: -20, vertical: -20)
        navController.tabBarItem.imageInsets = UIEdgeInsets(top: 3, left: 40, bottom: -3, right: -60)

        navController.tabBarItem.title = title.rawValue
        navController.tabBarItem.image = image.resize(width: 30, height: 30).withRenderingMode(.alwaysTemplate)

        navController.tabBarItem.badgeValue = ""

        return navController
    }
}

0 个答案:

没有答案