gpt4 book ai didi

ios - 如何在应用程序退出时保存 UISwitch 状态 (Swift)

转载 作者:可可西里 更新时间:2023-11-01 00:38:18 24 4
gpt4 key购买 nike

如何保存多个开关的状态,以便当应用程序退出并重新打开时,所有开关都不会处于退出前的相同状态。这是我为快速作业管理器编写的非常简单的代码。

//
// ViewController.swift
// HomeworkManager
//
// Created by Nate Parker on 9/2/14.
// Copyright (c) 2014 Nathan Parker. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


@IBAction func resetClicked(sender: AnyObject) {
spanish.setOn(false, animated: true);
algebra.setOn(false, animated: true);
amerCult.setOn(false, animated: true);
bio.setOn(false, animated: true);
col.setOn(false, animated: true);
}

@IBOutlet var spanish: UISwitch
@IBOutlet var algebra: UISwitch
@IBOutlet var amerCult: UISwitch
@IBOutlet var bio: UISwitch
@IBOutlet var col: UISwitch


}

最佳答案

AppDelegate 类中,在 applicationDidEnterBackground 中发布通知,这样当应用程序进入后台时,您的 View Controller 将能够收到通知:

func applicationDidEnterBackground(application: UIApplication!) {
NSNotificationCenter.defaultCenter().postNotificationName("kSaveSwitchesStatesNotification", object: nil);
}

在您的 View Controller 类中添加此代码:

override func viewDidLoad() {
super.viewDidLoad()
self.restoreSwitchesStates();

NSNotificationCenter.defaultCenter().addObserver(self, selector: "saveSwitchesStates", name: "kSaveSwitchesStatesNotification", object: nil);
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func saveSwitchesStates() {
NSUserDefaults.standardUserDefaults().setBool(spanish!.on, forKey: "spanish");
NSUserDefaults.standardUserDefaults().setBool(algebra!.on, forKey: "algebra");
NSUserDefaults.standardUserDefaults().setBool(amerCult!.on, forKey: "amerCult");
NSUserDefaults.standardUserDefaults().setBool(bio!.on, forKey: "bio");
NSUserDefaults.standardUserDefaults().setBool(col!.on, forKey: "col");

NSUserDefaults.standardUserDefaults().synchronize();
}

func restoreSwitchesStates() {
spanish!.on = NSUserDefaults.standardUserDefaults().boolForKey("spanish");
algebra!.on = NSUserDefaults.standardUserDefaults().boolForKey("algebra");
amerCult!.on = NSUserDefaults.standardUserDefaults().boolForKey("amerCult");
bio!.on = NSUserDefaults.standardUserDefaults().boolForKey("bio");
col!.on = NSUserDefaults.standardUserDefaults().boolForKey("col");
}

首先,添加 viewcontroller 作为应用程序进入后台时发布的通知的观察者。当触发此通知时,它将调用 saveSwitchesStates() 方法,该方法将开关状态保存在 NSUserDefaults 中。同样在 viewDidLoad() 中调用 restoreSwitchesStates(),它将从 NSUserDefaults

中读取开关状态的存储 bool 值

关于ios - 如何在应用程序退出时保存 UISwitch 状态 (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25652095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com