代码:
let MainTabFont:UIFont = UIFont.systemFontOfSize(11)
let MainTabSelectedColor:UIColor = UIColor(hexString: "#DB0079")!
let MainTabNonSelectedColor:UIColor = UIColor(hexString: "#646464")!
let taskVC = TaskViewController()
taskVC.tabBarItem = UITabBarItem(title: "任务", image: UIImage(named: "tab_task"), tag: TabTagTask)
taskVC.tabBarItem.selectedImage = UIImage(named: "tab_task_selected")
UITabBar.appearance().barTintColor = UIColor(hexString: "#F5F5F5")!
//set bar item font
let barItemFont = MainTabFont
for eachVC in self.viewControllers!{
eachVC.tabBarItem.setTitleTextAttributes([NSFontAttributeName: barItemFont, NSForegroundColorAttributeName: MainTabNonSelectedColor], forState: UIControlState.Normal)
eachVC.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: MainTabSelectedColor], forState: UIControlState.Selected)
}
gLog.debug("self.tabBarController?.view.frame=\(self.tabBarController?.view.frame)")
//default selection
self.selectedIndex = TabTagHom
效果:
然后颜色,也不知道如何设置为我要的,选中的文字时候的颜色
另外:
选中时的图片,没有变成我设置的tabBarItem.selectedImage
现在先要解决:
此处设置了tabBarItem.selectedImage,但是没效果的问题
但是:
之前的另外一个app,这么写代码,好像是工作的
tabBarItem.selectedImage not work
objective c – UITabBar not showing selected item images in ios 7 – Stack Overflow
改为:
let reportVC = ReportViewController()
// reportVC.tabBarItem = UITabBarItem(title: "报表", image: UIImage(named: "tab_report"), tag: TabTagReport)
// reportVC.tabBarItem.selectedImage = UIImage(named: "tab_report_selected")
reportVC.tabBarItem = UITabBarItem(title: "报表", image: UIImage(named: "tab_report"), selectedImage: UIImage(named: "tab_report_selected"))
依然没有效果:
难道是:
本身就已经起效果了,然后选中的图片,是透明的?
但是不是啊:
没有找到renderingMode初始化的选项:
然后对于:
reportVC.tabBarItem.selectedImage?.renderingMode = .AlwaysOriginal
却也报错:
Cannot assign to property: ‘renderingMode’ is a get-only property
去试试:
设置Assets.xcassets中的图片的属性中的Render As从Default改为:Original Image
结果:
真的生效了:
然后其他的图片也都改为对应的Original Image
然后就都可以正常显示了:
[总结]
iOS 9中,此处用代码设置tabBarItem的selectedImage,不论是:
初始化传递进入:
reportVC.tabBarItem = UITabBarItem(title: "报表", image: UIImage(named: "tab_report"), selectedImage: UIImage(named: "tab_report_selected"))
还是手动设置:
reportVC.tabBarItem = UITabBarItem(title: "报表", image: UIImage(named: "tab_report"), tag: TabTagReport)
reportVC.tabBarItem.selectedImage = UIImage(named: "tab_report_selected")
都无效。
最后改为:
去Assets.xcassets中,找到对应的图片,然后点击属性,把其中的:
Render As从默认的Default改为:Original Image
即可正常显示:
当选中Tab时,显示出对应的(此处的红色)的图片。