2017-11-21 11 views
0

간단한 앱이 있습니다. 앱에 대한 정보가 들어있는 Info라는 View Controller를로드하는 버튼이 있습니다. Info View Controller에는 "View Back"버튼이있어서 사용자는 다시 View Controller로 이동합니다. 메인 화면에는 int가 들어있는 countLabel라는 레이블이 있으며, 정보 화면으로 돌아가서 Int의 값을 기본값으로 되돌립니다. 다른 화면에서 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)" 
    } 

} 
+1

것은''countValue' – Torongo

+0

추가 self.countValue의 self.countValue'instead를 사용해보십시오 그러나 이것은 서로 반환 값을 유지하지 않는 것 컨트롤러보기. – Zakth

+0

'update()'func에 추가 했습니까? 'countLabel.text = "\ (self.countValue)"' – Torongo

답변

-3

다른 컨트롤러로 전환하기 전에 카운트 값을 userDefault에 저장하십시오. like

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

메인 뷰 컨트롤러로 돌아 오면 userDefault 값을 가져옵니다.

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

의견을 보내 주셔서 감사합니다.하지만이 코드를 어디에 추가해야할까요? 다른 컨트롤러를로드 할 때 버튼을 누르면 – Zakth

+0

에 감사드립니다. –

+0

나는이 추가 한 좋아요'code' @IBAction FUNC infoButton (_ 보낸 사람 : 모두) { 수 있도록 기본값 = UserDefaults.standard defaults.set (countValue, forKey : "있는 MyKey") }'code' 및 추가 AppDelegates에 대한 코드의 첫 번째 집합은 0으로 돌아갑니다. – Zakth

0

하기에 self.countLabel를 사용해보십시오 당신의 func update()

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

그래,이 업데이 트를 만들었지 만 주 ViewController로 돌아 가면 카운터는 이전에 보유한 Int를 유지하는 대신 0으로 재설정됩니다. – Zakth