如何将标签结果保留在secondViewController上?

时间:2018-12-31 06:27:36

标签: ios swift

我当前正在开发一个应用程序,并且遇到以下问题:我有我的mainVC( ReceiveInputVC ),在输入输入后,它会转到第二个VC( TimeLeftVC) ),并使用从mainVC收到的输入结果来更新其所有标签。我的问题是:在单击箭头以返回到mainVC之后,或者即使我关闭了应用程序,我如何在单击mainVC的箭头以转到secondVC时使我的标签显示与以前相同的值用户关闭了应用程序还是返回了主屏幕?

import UIKit

extension UIViewController {

    func hideKeyboard() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        view.addGestureRecognizer(tap)
    }

    @objc func dismissKeyboard() {
        view.endEditing(true)
    }

}

class ReceiveInputVC: UIViewController {

    @IBOutlet weak var hourglassButton: UIButton!

    @IBOutlet weak var whatIsYourAgeField: UITextField!
    @IBOutlet weak var ageToDieField: UITextField!

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

    @IBAction func arrowBtnPressed(_ sender: Any) {
        // When pressed should show go to TimeLeftVC and show last result from the first time user entered the inputs, if nothing has been typed yet and no data has been saved an alert should pop up asking the user to enter an input on both fields
    }

    @IBAction func hourglassBtnPressed(_ sender: Any) {

        let checkAgeField: Int? = Int(whatIsYourAgeField.text!)
        let checkDyingAgeField: Int? = Int(ageToDieField.text!)

        if (whatIsYourAgeField.text == "" || ageToDieField.text == "") || (whatIsYourAgeField.text == "" && ageToDieField.text == "") {
            alert(message: "You must enter an input on both fields")
        } else if checkAgeField! < 1 || checkDyingAgeField! > 100 {
            alert(message: "You must enter an age higher than 1 and a dying age lower than 100")
        } else if (checkAgeField! > checkDyingAgeField!) || (checkAgeField! == checkDyingAgeField!) {
            alert(message: "You must enter an age lower than a dying age")
        } else {
            performSegue(withIdentifier: "goToSecondScreen", sender: self)
        }

    }

    func alert(message: String, title: String = "Alert") {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Try Again", style: UIAlertAction.Style.default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }

    // Passing the data entered from ReceiveInputVC to TimeLeftVC
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToSecondScreen" {

            let destinationTimeLeftVC = segue.destination as! TimeLeftVC

            destinationTimeLeftVC.ageReceived = whatIsYourAgeField.text
            destinationTimeLeftVC.ageToDieReceived = ageToDieField.text
        }

    }

}

import CircleProgressBar

class TimeLeftVC: UIViewController {

    var ageReceived: String! // receive whatIsYourAgeField data from ReceiveInputVC
    var ageToDieReceived: String! // receive ageToDieField data from ReceiveInputVC

    @IBOutlet weak var yearsLeftLabel: UILabel!
    @IBOutlet weak var daysLeftLabel: UILabel!
    @IBOutlet weak var hoursLeftLabel: UILabel!

    @IBOutlet weak var progressBar: CircleProgressBar!

    override func viewDidLoad() {
        super.viewDidLoad()
        createResults()
    }

    func createResults() {

        if let userAge = Int(ageReceived), let dyingAge = Int(ageToDieReceived) {

            let yearsLeft = dyingAge - userAge
            let daysLeft = yearsLeft * 365
            let hoursLeft = daysLeft * 24

            // Update UI
            yearsLeftLabel.text = "\(yearsLeft)"
            daysLeftLabel.text = "\(daysLeft)"
            hoursLeftLabel.text = "\(hoursLeft)"

            let percentage = (CGFloat(yearsLeft) / CGFloat(dyingAge)) * 100
            let formatted = String(format: "%.1f", percentage)

            // Update Circle Progress Bar
            progressBar.setHintTextGenerationBlock { (progress) -> String? in
                return String.init(format: "\(formatted)%%", arguments: [progress])
            }

            progressBar.setProgress(percentage/100, animated: true, duration: 4.0)

        }

    }

在GitHub上的项目:https://github.com/mvvieira95/Time-Life.git

3 个答案:

答案 0 :(得分:1)

您可以使用Coredata或其他数据库或用户默认设置

用户默认实现:

 @IBAction func arrowBtnPressed(_ sender: Any) {
    UserDefaults.standard.set("your input values from text field or ...", forKey: "key")
}

在第二个视图控制器中获取它

 UserDefaults.standard.string(forKey: "key")

答案 1 :(得分:0)

您可以使用以下方法保存和还原状态

application:shouldSaveApplicationStateapplication:shouldRestoreApplicationStat

示例:

func application(_ application: UIApplication, 
            shouldSaveApplicationState coder: NSCoder) -> Bool {
   // Save the current app version to the archive.
   coder.encode(11.0, forKey: "MyAppVersion")

   // Always save state information.
   return true
}

func application(_ application: UIApplication, 
            shouldRestoreApplicationState coder: NSCoder) -> Bool {
   // Restore the state only if the app version matches.
   let version = coder.decodeFloat(forKey: "MyAppVersion")
   if version == 11.0 {
      return true
   }

   // Do not restore from old data.    
   return false
}

您可以在https://developer.apple.com/documentation/uikit/view_controllers/preserving_your_app_s_ui_across_launches?language=objc

中浏览文档

答案 2 :(得分:0)

谢谢大家,我想出了一个解决方案:

ReceiveInputVC类:UIViewController {

    @IBAction func arrowBtnPressed(_ sender: Any) {

    let defaults = UserDefaults.standard

    if let _ = defaults.object(forKey: "yearsSaved"), let _ = defaults.object(forKey: "daysSaved"), let _ = defaults.object(forKey: "hoursSaved") {
        performSegue(withIdentifier: "goToSecondScreen", sender: self)
    } else {
        alert(message: "You must first enter an input")
    }

}

TimeLeftVC类:UIViewController {

var ageReceived: String! // receive whatIsYourAgeField data from ReceiveInputVC
var ageToDieReceived: String! // receive ageToDieField data from ReceiveInputVC

@IBOutlet weak var yearsLeftLabel: UILabel!
@IBOutlet weak var daysLeftLabel: UILabel!
@IBOutlet weak var hoursLeftLabel: UILabel!

@IBOutlet weak var progressBar: CircleProgressBar!

override func viewDidLoad() {
    super.viewDidLoad()

    let defaults = UserDefaults.standard

    yearsLeftLabel.text = defaults.object(forKey: "yearsSaved") as? String
    daysLeftLabel.text = defaults.object(forKey: "daysSaved") as? String
    hoursLeftLabel.text = defaults.object(forKey: "hoursSaved") as? String

}

override func viewWillAppear(_ animated: Bool) {
    createResults()
}

func createResults() {

    if let userAge = Int(ageReceived), let dyingAge = Int(ageToDieReceived) {

        let yearsLeft = dyingAge - userAge
        let daysLeft = yearsLeft * 365
        let hoursLeft = daysLeft * 24

        // Update UI
        yearsLeftLabel.text = "\(yearsLeft)"
        daysLeftLabel.text = "\(daysLeft)"
        hoursLeftLabel.text = "\(hoursLeft)"

        // Store Data
        let defaults = UserDefaults.standard

        defaults.set(yearsLeftLabel.text, forKey: "yearsSaved")
        defaults.set(daysLeftLabel.text, forKey: "daysSaved")
        defaults.set(hoursLeftLabel.text, forKey: "hoursSaved")

        // Update Circle Progress Bar
        let percentage = (CGFloat(yearsLeft) / CGFloat(dyingAge)) * 100
        let formatted = String(format: "%.1f", percentage)

        progressBar.setHintTextGenerationBlock { (progress) -> String? in
            return String.init(format: "\(formatted)%%", arguments: [progress])
        }

        progressBar.setProgress(percentage/100, animated: true, duration: 4.0)

    }

}

现在当我回到视图时更新该ProgressBar时遇到麻烦...