2017-05-25 7 views
0

私がやりたかったのは、単純な画像をバックグラウンドとして持つカスタムボタンから始まるということです。ユーザーが「入力」ボタンをタップすると、カスタムボタンの画像が永久に変更され、ユーザーがアプリを再起動すると、最初の画像の代わりに2番目の画像が表示されます。 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にUser Defaultsのカスタムボタンの画像を保存する方法は?

答えて

1

ボタンをクリック、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 
    } 
} 

と、A より良い方法は、ボタンの通常の状態のための第1のイメージを設定し、選択されたステータスのための第2のイメージを設定することである。フラグ値が検出されたときに、ちょうどボタンの状態を設定します。

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

しかし、画像名をキーとして保存するほうがいいかもしれません...ボタン画像をロードすると、UDの値と画像のリストが一致します。これはカスタムアバターなどの柔軟性を可能にします(私はOPがこれと一緒に行くと思います) – Fluidity

+0

はい、シンプルなソリューションを提供しています。そして私は、参考のために、より良い練習を答えに加えました。 –

0

たい場合は、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 
    } 
} 
関連する問題