我在MFMessageComposeViewController
上更改导航栏的背景颜色时遇到问题。
我试过这段代码:
UINavigationBar.appearance().barTintColor = Configuration.Colors.navigationBarBackgroundColor
UINavigationBar.appearance().backgroundColor = UIColor.green
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont(name: "Roboto-Regular", size: 18)!, NSForegroundColorAttributeName: UIColor.white] as [String: AnyObject]
let composer = MFMessageComposeViewController()
self?.present(composer, animated: true) {
UIApplication.shared.statusBarStyle = .lightContent
}
这是行不通的。最奇怪的是,当我为MFMailComposeViewController
做同样的事情时,它确实有效。
我也尝试像这样直接在作曲家身上改变颜色。
composer.navigationBar.tintColor = Configuration.Colors.navigationBarBackgroundColor
我看起来找到了解决方法。不知何故设置composer.navigationBar.barTintColor
和UINavigationBar.appearance().barTintColor
不起作用。
解决方法是使用UINavigationBar.appearance().setBackgroundImage(...)
并设置UIImage,使用一种颜色作为背景
完整工作代码:
UINavigationBar.appearance().setBackgroundImage(UIImage.from(color: UIColor.green), for: .default)
let composer = MFMessageComposeViewController()
self?.present(composer, animated: true, completion: nil)
要使用一种颜色创建UIImage
:
extension UIImage {
static func from(color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}