查看另一个视图控制器时保存标签文本

时间:2017-11-21 06:30:32

标签: ios swift view controller

我有一个简单的应用程序。它有一个buttong,它加载一个名为Info的View Controller,它包含有关app的信息。在Info View Controller上有一个" Go Back"将用户带回主视图控制器的按钮。在主屏幕上有一个名为countLabel的标签,它包含一个Int,当进入信息屏幕并返回时,该Int的值重置为它的默认值0.如何保留该Int的值在另一个屏幕上?

//  ViewController.swift
//  Simple Count
//
//  Created by Jamie King on 11/19/17.
//  Copyright © 2017 Jamie King. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    var countValue = 0

    override func viewDidLoad() {
        super.viewDidLoad()



        // Do any additional setup after loading the view, typically from a nib.

    }
    @IBOutlet weak var countLabel: UILabel!


    @IBAction func countButton(_ sender: Any) {


        countValue = countValue + 1;
        update()
    }



    @IBAction func minusButton(_ sender: Any) {

     countValue = countValue - 1
        update()
    }



    @IBAction func resetButton(_ sender: Any) {

        countValue = 0
        update()    
    }



    @IBAction func infoButton(_ sender: Any) {



    }


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

    func update(){
        countLabel.text = "\(countValue)"
    }

}

2 个答案:

答案 0 :(得分:0)

尝试在self.countLabel

上使用func update()
func update(){
        self.countLabel.text = "\(self.countValue)"
}

答案 1 :(得分:-3)

在切换到另一个控制器之前,将您的计数值保存在userDefault中。像这样

let defaults = UserDefaults.standard
defaults.set(countValue, forKey: "count_value")

当您返回主视图控制器时,获取userDefault的值。

var countvalue = defaults.integer(forKey: "count_value")