如何在Swift中保存一个按钮的图像状态?

问题描述 投票:0回答:1

我有一个类似的按钮,当用户按下它的时候,图像变成了另一个图像。当我关闭我的应用程序并再次打开它时,我如何能够保存新的图像。我有下面的代码,我使用NSUserDefaults,但它不保存改变后的图像。下面是代码。

override func viewDidLoad() {
    super.viewDidLoad()

    UserDefaults.standard.set(true, forKey: "Change")

}

     @IBAction func addToLikes(_ sender: Any) {
    //progressView.isHidden = false

    if UserDefaults.standard.bool(forKey: "Change") {
         likedButton.setImage(UIImage(named: "selected_star"), for: .normal)
    } 
    }
swift xcode uibutton uikit
1个回答
0
投票

得到它的工作。

override func viewDidLoad() {
super.viewDidLoad()


    if UserDefaults.standard.bool(forKey: "starSelected") {
    likedButton.setImage(UIImage(named: "selected_star"), for: .normal)
        print("star selected")
    }

    if UserDefaults.standard.bool(forKey: "starNotSelected") {
    likedButton.setImage(UIImage(named: "not_selected_star"), for: .normal)
        print("star not selected")

    }

        }

}

 @IBAction func addToLikes(_ sender: Any) {
//progressView.isHidden = false

        likedButton.isSelected = !likedButton.isSelected

    if likedButton.isSelected {
            print("I am selected.")
            likedButton.setImage(UIImage(named: "selected_star"), for: .normal)
            UserDefaults.standard.set(false, forKey: "starNotSelected")
            UserDefaults.standard.set(true, forKey: "starSelected")

    } else {
            likedButton.setImage(UIImage(named: "not_selected_star"), for: .normal)
            UserDefaults.standard.set(false, forKey: "starSelected")
            UserDefaults.standard.set(true, forKey: "starNotSelected")

            print("I am not selected.")
    }
© www.soinside.com 2019 - 2024. All rights reserved.