如何在多个视图控制器中将图像从 UIImagePickerController 设置为 UIimages

How to set an image from UIImagePickerController to UIimages in multiple view controllers

编码新手,我想出了如何让用户select使用以下代码将照片作为背景

 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)

}

它有效,但仍未弄清楚如何保存它,但很快就会找到。

但是,如果我在所有视图中都有一个背景图像,我如何才能为所有视图设置相同的图像?

谢谢

我建议使用 NSNotificationCenter。

在您需要应用更改的每个视图控制器中,您会监听通知:

let nc = NSNotificationCenter.defaultCenter()
nc.addObserver(self, selector: "UpdateBackgroundImage:", name: "BackgroundImageChanged", object: image)

在每个视图控制器中,您都需要实现选择器,在本例中为 UpdateBackgroundImage。它们类似于:

func UpdateBackgroundImage(notification: NSNotification) {
    let backgroundImage = notification.userInfo!["image"] as UIImage
    // Your code to assign image to background
}

保存图像后,您可以post收到通知:

// Right after you assign backgroundImage.image = pickedImage  
let nc = NSNotificationCenter.defaultCenter()
let myDict = [pickedImage, "image"]
nc.postNotificationName("BackgroundImageChanged", object: nil, userInfo: myDict)

使用 NSNotificationCenter 的好处在于,当您添加需要更新背景图像的新视图时,您只需添加第一段代码。您无需更新选择图像的代码。

我建议您创建一个 BaseViewController,其中包含您的应用程序的常用功能,并在其中添加一个 imageView

之后继承所有 viewControllers 形式 BaseViewController 以便 imageView 也被继承,您可以设置它,它将与从 BaseViewController 继承的所有 viewControllers 相同。