Reputation: 431
New to coding, I've figured out how to let a user select a photo as their background with the following code
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
backgroundImage.contentMode = .ScaleAspectFill
backgroundImage.image = pickedImage
}
dismissViewControllerAnimated(true, completion: nil)
}
// Wallpaper function
@IBAction func wallpaperMenuPressed(sender: AnyObject) {
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
}
And it works, still haven't figured out how to save it but will find out soon.
But, if I have a backgroundImage in all my views, how do I get it to set the same image for all of them?
Thanks
Upvotes: 0
Views: 164
Reputation: 3130
I would suggest making use of NSNotificationCenter.
In each of your view controllers where you need to apply the change you listen for a notification:
let nc = NSNotificationCenter.defaultCenter()
nc.addObserver(self, selector: "UpdateBackgroundImage:", name: "BackgroundImageChanged", object: image)
In each of those view controllers you'll need to implement the selector, UpdateBackgroundImage
in this case. They would be similar to:
func UpdateBackgroundImage(notification: NSNotification) {
let backgroundImage = notification.userInfo!["image"] as UIImage
// Your code to assign image to background
}
After you save the image you can post a notification:
// Right after you assign backgroundImage.image = pickedImage
let nc = NSNotificationCenter.defaultCenter()
let myDict = [pickedImage, "image"]
nc.postNotificationName("BackgroundImageChanged", object: nil, userInfo: myDict)
The nice thing about using NSNotificationCenter
is that as you add new views that need to update the background images you just add the first bit of code. You don't need to update the code where you pick the images.
Upvotes: 1
Reputation: 8914
I suggest you to create a BaseViewController
in which common functionality of your app is there and also take a imageView
in that.
After that inherit all your viewControllers form BaseViewController
so that imageView
also be inherited and you can set it and it will be same all of your viewControllers inherited from BaseViewController
.
Upvotes: 1