【问题标题】:Save text of label when viewing another view controller查看另一个视图控制器时保存标签文本
【发布时间】:2017-11-21 06:30:32
【问题描述】:

我有一个简单的应用程序。它有一个按钮,它加载一个名为 Info 的 View Controller,其中包含有关应用程序的信息。在 Info View Controller 上有一个“Go Back”按钮,可将用户带回主 View Controller。在主屏幕上,有一个名为 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)"
    }

}

【问题讨论】:

  • 尝试使用self.countValue而不是countValue
  • 添加了 self.countValue 但从另一个视图控制器返回时似乎没有保留该值。
  • 您是否将其添加到您的update() func 中? countLabel.text = "\(self.countValue)"
  • 是的,我已经更新了更新函数以包含 self.countValue

标签: ios swift view controller


【解决方案1】:

尝试在您的func update() 上使用self.countLabel

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

【讨论】:

  • 好的,我已经进行了这个更新,但是当返回到主 ViewController 时,计数器重置为 0,而不是保留它之前持有的 Int。
【解决方案2】:

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

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

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

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

【讨论】:

  • 感谢您的反馈,但我不知道应该将此代码添加到哪里?谢谢
  • 加载其他控制器时点击按钮。
  • 好的,我已经添加了这个:code@IBAction func infoButton(_ sender: Any) { let defaults = UserDefaults.standard defaults.set(countValue, forKey: "MyKey") }@987654324 @ 并将第一组代码添加到 AppDelegates 但返回时 countValue 返回 0
  • 只检查你设置值时 countvale 的值,在 appdelegate 中 countvalue 肯定会为零,再次返回主视图控制器获取 userdefault 的值,我看到你正在将 countvalue 初始化为 0跨度>
  • 这是一个非常糟糕的解决方案。非常错误。用户默认值用于首选项和设置。用它在视图之间传递数据完全是一派胡言。当然“它有效”,但它很荒谬,是最糟糕的反模式之一。这是对资源的浪费,甚至可能成为未来问题的根源。
猜你喜欢
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
  • 1970-01-01
  • 2012-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
相关资源
最近更新 更多