简体   繁体   English

将背景图像存储在userdefaults中

[英]storing background images in userdefaults

I need to be able to set the background image for this button. 我需要能够为该按钮设置背景图像。 I need to store this so after the app closes the background image is the same. 我需要存储此内容,以便在应用关闭后,背景图像是相同的。

eventsFirstButton.backgroundColor = UIColor(patternImage: UIImage(named: "events")!)

You could just save the state: 您可以保存状态:

Correct answer: 正确答案:

UserDefaults.standard.set(true, forKey: "TestAnswer1")
//If the answer is incorrect set to false

On load: 负载:

 if UserDefaults.standard.bool(forKey: "TestAnswer1") {
      view.backgroundColor = UIColor.green
      // or any other logic
 } else {
      view.backgroundColor = UIColor.red
      // or any other logic
 } 

It's better to save it as base64string , you don't want to store large value to UserDefaults. 最好将其另存为base64string ,而不希望将大值存储到UserDefaults中。

To encode UIImage use this: 要对UIImage进行编码,请使用以下代码:

let image = UIImage()
let data = image.pngData()
let imageBase64String = data?.base64EncodedString()
UserDefaults.standard.set(imageBase64String, forKey: "encodedImage")

And for decoding and retrieving UIImage use this: 对于解码和检索UIImage使用以下命令:

if let imageBase64String = UserDefaults.standard.value(forKey: "encodedImage"),
    let url = URL(string: String(format:"data:application/octet-stream;base64,%@",imageBase64String))
{
    do
    {
        let data =  try Data(contentsOf: url) 
        let image = UIImage(data: data)
    }
    catch let error
    {
        print("Error decoding image")    
    }
}

If you really need to save the PNG, JPEG images locally, use CoreData to store them on the device. 如果您确实需要在本地保存PNG,JPEG图像,请使用CoreData将它们存储在设备上。

You can use UserDefaults to save your image 您可以使用UserDefaults保存图像

Save

if let image = eventsFirstButton.imageView?.image {
            let imageData = image.pngData()
            UserDefaults.standard.set(imageData, forKey: "imageData")
        }

Retrieve 取回

if let imageData = UserDefaults.standard.data(forKey: "imageData") {
            print("IMG data: ", imageData)
            // your code here
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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