在 MFMessageComposeViewController 上设置 NavigationBar 背景颜色

Set NavigationBar background color on 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上改变颜色

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