首页 > 解决方案 > 如何在 secondViewController 上保留标签结果?

问题描述

我目前正在开发一个应用程序,但遇到以下问题:我有我的 mainVC ( ReceiveInputVC ),在我输入输入后,它会转到 secondVC ( 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

标签: iosswift

解决方案


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

用户默认实现:

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

在第二个视图控制器中得到它

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

推荐阅读