How to Add the Same Background Image to All Views in My iOS App Using Swift

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

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

Sharing a Background Image Across Multiple View Controllers

A better way of doing this with swift when compared to subclassing, write an extension and call your method in all your view controllers.

extension UIViewController{

func setCustomBackgroundImage(){

self.view.backgroundColor = UIColor(patternImage: UIImage(named:"yourImageFromXcAssets")!)

//or

let bgImage = UIImageView(image: UIImage(named: "yourImageFromXcAssets"))
self.view.addSubview(bgImage)
}
}

and in your view controllers just call it like regular UIViewController class methods,

class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.setCustomBackgroundImage()
}

or write a category over UIViewController with Objective-C

#import <UIKit/UIKit.h>

@interface UIViewController (customBackground)

- (void)setCustomBackgroundImage;

@end

#import "UIViewController+customBackground.h"

@implementation UIViewController (customBackground)

- (void)setCustomBackgroundImage{
[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"yourImageFromXcAssets"]]];
//or
UIImageView *bgImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"yourImageFromXcAssets"]];
bgImage.frame = self.view.frame;
[self.view addSubview:bgImage];
}

@end

And the same approach with Objective C as well,

 [self setCustomBackgroundImage]; 

I am using a view controller extension to manage all my styles, colors and appearances across my app.

Set Absolute Background for Entire App

The simplest way is to add a UIImageView to your root window and make sure all of your other views have transparent backgrounds;

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.

let window=self.window!

let backgroundView=UIImageView(frame: window.frame)

backgroundView.image=UIImage(named: "Background.JPG")!

window.addSubview(backgroundView)

return true
}

or in Objective-C

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.

UIWindow *window=application.windows.firstObject;
UIImageView *imageView=[[UIImageView alloc] initWithFrame:window.frame];

imageView.image=[UIImage imageNamed:@"Background.jpg"];

[window addSubview:imageView];
return YES;
}

Multiple ViewControllers with same background

Solution 1

Create a class called MyBackground:

class MyBackground {
class func addBackgroundImage() {
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "file")?.drawInRect(self.view.bounds)

let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()

view.backgroundColor = UIColor(patternImage: image)
}
}

If you want to call it in your AViewController, simply call MyBackground.addBackgroundImage()

Solution 2

Create a ViewController called MyViewController:

class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
addBackgroundImage()
}

func addBackgroundImage() {
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "file")?.drawInRect(self.view.bounds)

let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()

view.backgroundColor = UIColor(patternImage: image)
}
}

If you AViewController want to set this image, simply do like this:

AViewController: MyViewController //AViewController is a subclass of MyViewController

For example: I have an image call background, and I will set it as a background image of my ViewController:

Sample Image

If I just add it in one line as @startupthekid said:

Sample Image

If I add it as I said:

Sample Image

change all view controller background in swift

You have a few options.. what option is best depends on your needs really.

As Woodstock mentioned in his answer, you could use NotificationCentre, I wont re-explain that.

Another option would be to store the image name in UserDefaults that you are going to use for the background image.

any time you change the background... set the value

 UserDefaults.standard.set(imageName, forKey "backgroundImageName")

Then in each view controller, just load the value on viewWillAppear

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated: animated)
if let backgroundImageName = UserDefaults.standard.string(forKey: "backgroundImageName") {
self.backgroundImageView.image = UIImage(named: backgroundImageName)
}
}

Both of these options are not very easy to unit test though. You could use Mocks to test it.

A bonus of this method is that it will 'remember' the setting inbetween the user restarting the app.

An example of how you might reduce code repetition using subclassing:

class WallpaperedViewController: UIViewController {

lazy private var imageView: UIImageView = {
let imageView = UIImageView()
view.addSubview(imageView)
view.sendSubview(toBack: imageView)
return imageView
}()

private func setWallPaperImage() {
let imageName = UserDefaults.standard.string(forKey: "backgroundImageName")

let image = UIImage(named: imageName!)
imageView.image = image
//imageView.contentMode = .scaleAspectFill

imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
imageView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
imageView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

self.setWallPaperImage()
}
}

Then for each ViewController that has this background image wallpaper just extend this class:

class SomeViewController: WallpaperedViewController {}

Image as background for every view

Probably the easiest way would be:
Set your image as colorWithPatternImage as backgroundColor of your UITabBarController like this:

[tabbarController.view setBackgroundColor:UIColor colorWithPatternImage:yourImage];

then make sure to set the backgroundColor of the views of all it's viewControllers to clearColor.

How to set a background image in Xcode using swift?

override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png"))
}


Related Topics



Leave a reply



Submit