gpt4 book ai didi

swift - (Swift) 选项卡栏项目 : Custom Selected Image with Rendering asOriginal is Not Showing

转载 作者:行者123 更新时间:2023-11-30 12:48:06 24 4
gpt4 key购买 nike

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

目标:将选项卡栏项目选定的图像设置为自定义图像。

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

| |UITabBarController|UITabBarController => | UI View Controller | (带有 Storyboard的设置)

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

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

| |UITabBarController|UITabBarController => | UINavigationController | 导航 Controller => | UI View Controller | (使用 Storyboard设置 - see here )

与上面的代码类似,但(以编程方式)将 UICollectionView subview 添加到 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
...
}
}

一些可能有帮助的事情:

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

发生什么事了?

最佳答案

我扩展了 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

}

}

这将有助于访问 tabBar.items,而无需加载任何 View Controller (选项卡 0 的第一个 View Controller 除外)。

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)
}

}

例如,如果要更改选项卡 2 选定的图像,请在 viewDidLoad: 上打断点:在第二个 View Controller 上,您会发现断点没有命中,这就是选项卡项的图像不会命中的原因已更新。

关于swift - (Swift) 选项卡栏项目 : Custom Selected Image with Rendering asOriginal is Not Showing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41361058/

24 4 0