以编程方式创建UITabBarController子视图不加载UITabBarItem图像

时间:2017-01-23 11:09:08

标签: ios swift uikit uitabbarcontroller

我正在程序性地将故事板加载到UITabBarController中但由于某种原因UITabBarItem没有加载图像或者所有的selectedImage,除了第一个Tab没有加载

Appearance when app first loads

但如果您点按其他标签图标

After tabing through all tabs

加载故事板示例

break

的UITabBarController

import UIKit

class ProfileViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let defaultImag = UIImage(named: "Profile")?.withRenderingMode(.alwaysOriginal)
        let selectedImag = UIImage(named: "Profile_selected")?.withRenderingMode(.alwaysOriginal)

        self.tabBarItem = UITabBarItem(title: nil, image: defaultImag, selectedImage: selectedImag)
        self.tabBarItem.imageInsets = UIEdgeInsets(top: 10, left: 0, bottom: -10, right: 0);
    }

}

1 个答案:

答案 0 :(得分:0)

private func createTabForStoryBoard(storyBoardName: String, title: String, imageName :String, tag: Int) -> (UINavigationController) {

        let storyboard  = UIStoryboard(name: storyBoardName as String, bundle: nil)
        let viewController  = storyboard.instantiateInitialViewController() as! UIViewController

        let image = UIImage(named: imageName)
        let tabBarItem:UITabBarItem = UITabBarItem.init(title: NSLocalizedString(title, comment: "Tab Bar Names") , image: image, tag: 0)

        viewController.tabBarItem = tabBarItem
        return viewController

    }


    // MARK: Custom Methods

    func setTabBarViewControllers() {
        let discoverViewController = self.createTabForStoryBoard("Discover", title: "Discover", imageName: "<image-name>", tag: 1)

        let favouritesViewController = self.createTabForStoryBoard("Favourites", title: "Favourites", imageName: "<image-name>", tag: 2)

        let profileViewController = self.createTabForStoryBoard("Profile", title: "Profile", imageName: "<image-name>", tag: 3)

        let tabBarViewControllers = [discoverViewController, favouritesViewController, profileViewController]
        self.viewControllers = tabBarViewControllers
    }