Swift - 如何保存图像按钮?

时间:2017-04-25 04:20:56

标签: swift

如何保存按钮的开关值?我有一个On-Off按钮,当用户打开应用程序并单击Off按钮时,我希望应用程序保存它,以便在重新打开应用程序时,按钮的值仍为Off。希望这可以通过使用User Defaults来完成。我的代码:

class ViewController: UIViewController {
    var soundEnable:Bool = true
    var soundImage:UIImage?

    @IBAction func soundbtn(_ sender: UIButton) {
        let soundButton = sender

        if (soundEnable) {
            soundImage = UIImage.init(named: "mute.png")
            soundEnable = false
        } else {
            soundImage = UIImage.init(named: "sound.png")
            soundEnable = true
        }

        soundButton.setImage(soundImage, for: UIControlState.normal)
    }
}

See image

3 个答案:

答案 0 :(得分:0)

请在viewDidLoad方法

中写下这些行
override func viewDidLoad() {
    super.viewDidLoad()
    if (UserDefaultsManager.useDarkTheme) {
        soundImage = UIImage.init(named: "mute")
        print(UserDefaultsManager.useDarkTheme)

} else {
      soundImage = UIImage.init(named: "sound")
      print(UserDefaultsManager.useDarkTheme)
    }
}

答案 1 :(得分:0)

  1. 您需要在viewDidLoad中再设置一个图像。
  2. 您为setImage输入了错误的参数:

    soundButton.setImage(soundImage,for:UIControlState())

  3. 它应该是一个特定的状态:

    soundButton.setImage(soundImage, for: UIControlState.normal)
    

答案 2 :(得分:0)

@IBOutlet weak var backgroundImage: UIImageView!

let ImageNameKey = "ImageNameKey"

let soundbg = UIImage(named: "sound")
let mutebg = UIImage(named: "mute")

override func viewDidLoad() {
    super.viewDidLoad()

    //Sound.play(file: "bg", fileExtension: "wav", numberOfLoops: -1)

    let defaults = UserDefaults.standard
    if let name = defaults.string(forKey: ImageNameKey) {
        if (name == "sound") {
            backgroundImage.image = soundbg
        } else {
            backgroundImage.image = mutebg
        }
    }
}

@IBAction func clickbtn(_ sender: UIButton) {

    let defaults = UserDefaults.standard

    if(backgroundImage.image == soundbg){
        backgroundImage.image = mutebg
        defaults.set("mute", forKey: ImageNameKey)
        Sound.enabled = false
    }
    else{
        backgroundImage.image = soundbg
        defaults.set("sound", forKey: ImageNameKey)
        Sound.enabled = true
    }
}