设置后如何让Swift记住UIImage颜色

时间:2019-03-06 06:30:11

标签: ios swift

我刚刚开始学习Swift,并且正在构建一个简单的应用程序。主页只是一个表:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let theData: [String] = ["BRDA", "HFH", "ENGRII", "HSSB", "GRVT"]
    let cellReuseIdentifier = "cell"

    @IBOutlet weak var tableView: UITableView!
    @IBAction func unwindToHome(segue: UIStoryboardSegue) { }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.frame = CGRect(x: 0, y: 200, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height-600)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

        self.view.addSubview(tableView)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return theData.count
    }

    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
        cell.textLabel?.text = theData[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if (indexPath.row == 0) {
            // segue to BRDA
            performSegue(withIdentifier: "toBRDA", sender: nil)
        } else {
            print("Will add later! You clicked on \(theData[indexPath.row]).")
        }
    }
}

我使第一个条目可单击,然后将其连接到另一个控制器。这个新的控制器有一个UIImage对象,当您点击它时,它只是改变颜色。

class BRDAController: UIViewController {

    @IBOutlet weak var thePic: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        var tapGesture = UITapGestureRecognizer()
        tapGesture = UITapGestureRecognizer(target: self, action: #selector(BRDAController.didTap(_:)))
        tapGesture.numberOfTapsRequired = 1
        tapGesture.numberOfTouchesRequired = 1
        thePic.addGestureRecognizer(tapGesture)
        thePic.isUserInteractionEnabled = true
        thePic.backgroundColor = UIColor.yellow
        // Do any additional setup after loading the view.
    }

    @objc func didTap(_ sender: UITapGestureRecognizer) {
        // User tapped at the point above. Do something with that if you want.
        if thePic.backgroundColor == UIColor.yellow {
            thePic.backgroundColor = UIColor.green
        } else {
            thePic.backgroundColor = UIColor.yellow
        }
    }

    @IBAction func backButton(_ sender: Any) {
        self.performSegue(withIdentifier: "goBackHome", sender: nil)
    }
}

我使用轻松的方法返回家中,但是当我返回另一个控制器时,状态已重置(颜色已设置为其默认的黄色)。我该如何使代码“记住”其先前状态?

1 个答案:

答案 0 :(得分:4)

这取决于用例。如果要将数据保存为...

  • ...退出并重新启动应用程序后,将其保存为用户默认设置
  • ...仅会话,当返回上一个VC时,请使用委托方法

会话后:UserDefaults

@IBAction func backButton(_ sender: Any) {
    UserDefaults.standard.set(thePic.backgroundColor, forKey: "color")
}

...使用here中的UserDefaults扩展名。

下次启动应用程序时,请阅读如下颜色:

let color = UserDefaults.standard.color(forKey: "color")

仅会话:委托方法

创建委托协议:

protocol BRDAControllerDelegate: class {
    func brdaController(_ brdaController: BRDAController, willDismissPassing data: [String: Any])
}

然后,创建一个委托属性:

class BRDAController: UIViewController {
    weak var delegate: BRDAControllerDelegate?

在解雇之前,请通知代表:

    @IBAction func backButton(_ sender: Any) {
        delegate?.brdaController(self, willDismissPassing: ["color": thePic.backgroundColor])
        // dismiss here
    }
}

在呈现视图控制器内部,继承自委托方法:

class ViewController: ..., BRDAControllerDelegate {
    func brdaController(_ brdaController: BRDAController, willDismissPassing data: [String: Any]) {
        if let color = data["color"] as? UIColor {
            // do something with your color here
        }
    }

并在过渡之前将委托设置为self

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)
    if let brdaVC = segue.destination as? BRDAController {
        brdaVC.delegate = self
    }
}

此外,我建议您关闭视图控制器,而不要创建新的序列:

@IBAction func backButton(_ sender: Any) {
    // embedded in navigation controller? use:
    navigationController?.popViewController(animated: true)
    // OR, no navigation controller? use:
    dismiss(animated: true)
}