如何使用Swift 3中的用户默认值保存自定义按钮的图像?

问题描述:

我想要做的是该应用程序以一个自定义按钮开始,该按钮具有简单的图像作为背景。如果用户点击“输入”按钮,自定义按钮的图像将永久更改,如果用户重新启动应用程序,则第二个图像将仍然显示,而不是第一个。 This is the image when the user starts the app for the first time. This is the image that the user will see as he/she taps the enter button, and that image is saved permanently.如何使用Swift 3中的用户默认值保存自定义按钮的图像?

当按钮点击后,在UserDefaults保存的标志值:

UserDefaults.standard.set("1", forKey: "kIsButtonSelected") 
UserDefaults.standard.synchronize() 

当重新启动应用程序,检查值并设置按钮图像:

if let isButtonSelected = UserDefaults.standard.object(forKey: "kIsButtonSelected") as? String { 
    if isButtonSelected == "1" { 
     //set the second image 
    } 
} 

而且一更好的做法是为按钮的正常状态设置第一个图像,第二个为选定的状态。而刚刚设定的检测标志值时,该按钮的状态:

button.isSelected = true //the image will be changed to the second one automatically. 
+0

这是不是一个坏的方法,但最好将图像名称存储为关键字......然后,加载按钮图像时,只需将UD的值与图像列表相匹配即可。这让我有更多的灵活性,比如自定义头像等等(这是我认为OP会与之相匹配的地方) – Fluidity

+0

是的,我只是提供简单的解决方案让Francisco很快理解。我在回答中加入了一个更好的做法以供参考。 –

我会做这个,所以这样如果需要的话,你可以使用超过1张图片:

// Put a all of your images that you want here: 
var imageDictionary = ["smilyface": UIImage(named: "smilyface.png"), 
         "person" : UIImage(named: "person.png"), 
         // and so on... 
] 

// Use this whenever you want to change the image of your button: 
func setCorrectImageForButton(imageName name: String) { 
    UserDefaults.standard.set(name, forKey: "BUTTONIMAGE") 
} 

// Then use this to load the image to your button: 
// myButtonImage = grabCorrectImageForButton() 
func grabCorrectImageForButton() -> UIImage? { 

    guard let imageKey = UserDefaults.standard.string(forKey: "BUTTONIMAGE") else { 
    print("key not found!") 
    return nil 
    } 

    if let foundImage = imageDictionary[imageKey] { 
    return foundImage 
    } 
    else { 
    print("image not found!") 
    return nil 
    } 
}