swiftuiactivityviewcontrollerbartintcolor

Change barTintColor in activityViewController


I have a swift 4 / iOS 12 application that uses a custom navbar barTintColor for all view controllers and is set in appDelegate.swift like so:

UINavigationBar.appearance().barTintColor = UIColor(red: 229/255, green: 80/255, blue: 57/255, alpha: 1.0)

However, id'l like to change the color when I present an activityViewController so that the mail compose view get a white barTint. I've achieved this by doing:

let activityViewController = UIActivityViewController(activityItems: textShare , applicationActivities: nil)
            activityViewController.popoverPresentationController?.sourceView = self.view
            self.present(activityViewController, animated: true, completion: { () in

                UINavigationBar.appearance().barTintColor = UIColor.white
            })

But when I dismiss the activityViewController the tintColor of the navbar has changed for the whole application. This is not the behavior that I want. I want the tintColor to be set back when I dismiss activityViewController, but I can't figure out how to catch the "willDisappear" function so I can set it back.


Solution

  • UIActivityViewController is subclass of UIViewController so you can override its method like viewWillDisappear, viewDidAppear, etc.

    So first create your custom subclass of UIActivityViewController and then override its viewWillDisappear method and declare what should happen when ViewController will disappear.

    class YourActivityViewController: UIActivityViewController {
        override func viewWillDisappear(_ animated: Bool) {
            UINavigationBar.appearance().barTintColor = UIColor(red: 229/255, green: 80/255, blue: 57/255, alpha: 1.0)
        }
    }
    

    then just declare your activityViewController as your UIActivityViewController subclass

    let activityViewController = YourActivityViewController(activityItems: textShare , applicationActivities: nil)