在不同的View Controller中添加整数

时间:2017-08-16 08:13:56

标签: swift xcode int

我希望能够将View Controller 1中按钮的整数加到View Controller 2中的标签上。我试图通过单独的swiftFile传递数字。 我以为我有正确的代码,但数字不在totalSumLabel中加在一起。 描述是由X-cide强制执行的。没有它我得到错误: “init已重命名为init(描述)”

inport UIKit


class addPrice: NSNumber {
var allSum: Int = 0
}

View Controller 1中的代码:

class ViewController1: UIViewController {
var myTotal: addPrice?


 @IBAction func button1(_ sender: UIButton) {
     myTotal?.allSum += 190
    }
@IBAction func button2(_ sender: UIButton) {
     myTotal?.allSum += 240
    }

View Controller 2中的代码:

class ViewController2: UIViewController {
var myTotal: addPrice?

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    totalSumLabel.text = String (describing: myTotal?.allSum)

1 个答案:

答案 0 :(得分:0)

我会实现这样的服务:

import Foundation
import UIKit

class DataFactory {

    var allSum:Int = 0

    static let sharedInstance : DataFactory = {
        let instance = DataFactory()
        return instance
    }()

}

您可以从每个ViewController获取您的属性值,如下所示:

let allSum = DataFactory.sharedInstance.allSum

或者从任何地方设置这样的财产:

DataFactory.sharedInstance.allSum += 1

在特定的ViewControllers中保存全局属性不是一个好主意