简体   繁体   中英

How can I add the same background image to all views in my ios app using swift?

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM