在 MFMessageComposeViewController 上设置导航栏背景颜色



我在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.barTintColorUINavigationBar.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!
}
}

最新更新