我尝试更改Tab Bar
项的默认灰色,但Xcode发现错误。我使用了一些代码,代码是:
import UIKit
extension UIImage {
func makeImageWithColorAndSize(color: UIColor, size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(CGRectMake(0, 0, size.width, size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
class SecondViewController: UIViewController {
let tabBar = UITabBar()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
UITabBar.appearance().selectionIndicatorImage = UIImage().makeImageWithColorAndSize(UIColor.blueColor(), size: CGSizeMake(tabBar.frame.width/CGFloat(tabBar.items!.count), tabBar.frame.height))
}
所以我把它放在SecondViewController
中就像测试一样,当我在Xcode Simulator上运行应用程序时它会崩溃并在日志中显示错误(控制台)致命错误:在展开Optional值时意外发现nil
我认为问题在于:
UITabBar.appearance().selectionIndicatorImage = UIImage().makeImageWithColorAndSize(UIColor.blueColor(), size: CGSizeMake(tabBar.frame.width/CGFloat(tabBar.items!.count), tabBar.frame.height))
因为当我删除这部分代码时,不会发生错误。 有人能帮助我吗?
答案 0 :(得分:1)
代码中创建UITabBar
对象(例如let tabBar = UITabBar()
)的问题,此对象与表单上的选项卡无关。您的tabBar
是一个新的空对象,不包含任何UITabBarItem
个对象,当您调用它时:
UITabBar.appearance().selectionIndicatorImage = UIImage().makeImageWithColorAndSize(UIColor.blueColor(), size: CGSizeMake(tabBar.frame.width/CGFloat(tabBar.items!.count), tabBar.frame.height))
尝试执行此操作时会发生错误:tabBar.items!.count
。您正在尝试解包可选的items
数组[UITabBarItem]?
,而nil
因为tabBar
是空对象且没有项目。
要解决此问题,您需要从当前UITabBar
引用UITabBarController
,例如:
class SecondViewController: UIViewController {
var tabBar: UITabBar?
override func viewDidLoad() {
super.viewDidLoad()
tabBar = self.tabBarController!.tabBar
tabBar!.selectionIndicatorImage = UIImage().makeImageWithColorAndSize(UIColor.blueColor(), size: CGSizeMake(tabBar!.frame.width/CGFloat(tabBar!.items!.count), tabBar!.frame.height))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}