【问题标题】:(Swift) Tab Bar Item: Custom Selected Image with Rendering asOriginal is Not Showing(Swift) 选项卡栏项:未显示以原样渲染的自定义选定图像
【发布时间】:2016-12-28 11:24:02
【问题描述】:

首先,我是 Swift 的新手,如果我遗漏了一些明显的东西或使用了错误的术语,我深表歉意。

目的:将标签栏项目选中的图片设置为自定义图片。

以下设置有效(所选项目是自定义图像):

| UITabBarController | => | UIViewController | (带故事板的设置)

class MyViewController: UIViewController {  
    override func viewDidLoad() {
        super.viewDidLoad()
        let customSelectedImage = UIImage (named: "selected-image")?.withRenderingMode(.alwaysOriginal)
        self.tabBarItem.selectedImage = customSelectedImage
    }
}

但此设置不起作用(所选项目具有默认蓝色):

| UITabBarController | => | UINavigationController | => | UIViewController | (带故事板的设置 - see here

与上面类似的代码,但是(以编程方式)将 UICollectionView 子视图添加到 UIViewController。

class MyViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {  
    override func viewDidLoad() {
        super.viewDidLoad()
        let customSelectedImage = UIImage (named: "selected-image")?.withRenderingMode(.alwaysOriginal)
        self.tabBarItem.selectedImage = customSelectedImage
        ...
        //Some UICollectionView related code
        ...
    }
}

一些可能有用的东西:

  • 在调试会话中 (see print screen) => 查看 UI 层次结构:所选项目(标记为 UITabBarSwappableImageView 类)具有正确的自定义图像,但色调为默认蓝色。我尝试了不同的自定义图像,看起来好像它们被另一个(默认?)视图隐藏了......
  • 如果我在 AppDelegate.swift 应用程序(... didFinishLaunchingWithOptions ...) 函数中更改 UITabBar.appearance().tintColor = UIColor.red,则所选项目具有红色(相对于蓝色)色调。

发生了什么事?

【问题讨论】:

    标签: swift image uinavigationcontroller uitabbarcontroller uitabbaritem


    【解决方案1】:

    我扩展了 UITabBarController:

    extension UITabBarController {
    
        func updateTabBarItem(tab: Int, image: UIImage?) {
    
            guard let tabItems = tabBar.items, tab < tabItems.count && tab >= 0
                else { return }
    
            let tabItem = tabItems[tab]
            tabItem.image = image?.withRenderingMode(.alwaysOriginal)
            tabItem.selectedImage = tabItem.image
    
        }
    
    }
    

    这将有助于在不加载任何视图控制器(选项卡 0 的第一个视图控制器除外)的情况下访问 tabBar.items。

    class MyViewController: UIViewController {
    
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            tabBarController?.updateTabBarItem(tab: 1, image: UIImage(named: "selected-image")) // update the second tab's image here (just for example)
        }
    
    }
    

    例如,如果你想改变 tab 2 选中的图像,在 viewDidLoad 上打断点:在第二个视图控制器上,你会发现断点没有命中,这就是为什么 tab item 的图像不会更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-17
      • 1970-01-01
      • 2015-01-15
      • 2021-01-02
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多