1

I want to be able to add a background image to my ios app that applies for all views and not having to add this image to every single view. Is it possible to add an image to UIWindow or something?

Now, when I do a transition, the background of the new view also "transitions" over my previous view even though its the same background. I want to be able to only se the content transition, and not the background, which is the same.

mrlarssen
  • 325
  • 8
  • 19
  • 1
    You should be able to achieve this by subclassing UIWindow and overriding `drawRect` to draw your image. And then setting UIColor.clearColor as background color for all views. – Cristik Jan 12 '16 at 10:59

1 Answers1

3

You should be able to achieve this by:

  1. subclassing UIWindow and overriding drawRect to draw your image; details about subclassing UIWindow here
  2. and then by using UIAppearance to control the background colour for the rest of the views in your app (you should set it to clearColor); details about this here, though I think you'll need to subclass the views used by your controllers in order to cope with the note in the accepted answer

A basic implementation could look like this:

class WallpaperWindow: UIWindow {

    var wallpaper: UIImage? = UIImage(named: "wallpaper") {
        didSet {
            // refresh if the image changed
            setNeedsDisplay()
        }
    }

    init() {
        super.init(frame: UIScreen.mainScreen().bounds)
        //clear the background color of all table views, so we can see the background
        UITableView.appearance().backgroundColor = UIColor.clearColor()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func drawRect(rect: CGRect) {
        // draw the wallper if set, otherwise default behaviour
        if let wallpaper = wallpaper {
            wallpaper.drawInRect(self.bounds);
        } else {
            super.drawRect(rect)
        }
    }
}

And in AppDelegate:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow? = WallpaperWindow()
Community
  • 1
  • 1
Cristik
  • 30,989
  • 25
  • 91
  • 127