快速将计算的数据传递回上一个视图控制器 [英] Swift passing calculated data back to previous view controller

查看:71
本文介绍了快速将计算的数据传递回上一个视图控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建我的第一个简单的预算应用程序.基本上,我会输入一些用户输入信息,例如月收入和储蓄目标.然后,他们单击开始",&该应用会计算诸如他们的每日预算之类的内容.

I am creating my first simple budgeting app. Basically, I take a few user inputs like monthly income & savings goal. Then they click "start", & the app calculates stuff such as, their daily budget etc.

我在这里遇到麻烦了.经过所有计算后,我会显示您每天可以花多少钱"(例如,每天20美元),我会在原始屏幕上通过搜索结果从搜索结果中继续前进.

Here I'm running into trouble. After all the calculations, I display "how much you can spend each day" (e.g. $20 a day), which I pass forward through segues from their original inputs on the original screen.

现在,在此VC(UserInfoVC)中,我创建了一个按钮,可让他们添加自己今天花了多少钱.因此,当他们单击此增加支出"按钮时,我打开一个新的VC(AddSubtractMoney),在其中提供一个计算器,他们可以在其中输入他们今天花费的金额(即12美元),然后单击提交".

Now, in this VC (UserInfoVC) I created a button which lets them add how much money they spent today. So when they click this "add money spent" button, I open a new VC (AddSubtractMoney) where I present a calculator where they can enter how much they spent today (i.e. $12) and click submit.

我将他们的输入与他们的每日预算进行比较,以获得新的每日预算.

I run their input compared to their daily budget to get a New daily budget.

现在,我无法向后传递此更新的数字,以将其显示在标签为"dailySpendingLimitLabel"的先前的VC上.我知道搜寻并不是向后传递数据的最佳方法.

Now, I'm having trouble passing this updated number backwards, to display it on the previous VC on the label "dailySpendingLimitLabel". I know segues are not the best way to go about passing data backwards.

我尝试了闭包,但最终迷失了语法,协议和委托(这是我第二个月的编码).

I've tried closures, but I end up getting lost in the syntax, and protocols and delegates (it's my 2nd month coding).

是否有一种简单的方法可以将这些数据传递回先前的VC,并在先前的显示标签中填充数据?

Is there a simple way to achieve passing this data back to the previous VC and populating the data in that previous display label?

下面是代码.

第一个代码段来自UserInfoVC,我在其中显示了他们通过序列找到的最初输入的数据.第二个片段来自AddSubtractMoney类,我在其中放置了计算器,并在一个函数内创建了一个对象"newestUpdate",该函数使我能够计算出他们在计算器上输入的数字减去以前的每日预算.为了得出一个新的预算,我想向后显示给UserInfoVC.

The First snippet is from the UserInfoVC where I display their originally entered data that I segued through. The Second snippet is from the AddSubtractMoney class where I placed the calculator and created an object "newestUpdate" inside a function that allows me to calculate the number they entered on the calculator minus their old daily budget. To arrive at a new budget which I want to present backwards to the UserInfoVC.

class UserInfoViewController : ViewController {

var userNamePassedOver : String?
var userDailyBudgetPassedOver : Double = 99.0
var userDailySavingsPassedOver : Double = 778.00
var userMonthlyEarningsPassedOver : Double?
var userDesiredSavingsPassedOver : Double?
var newAmountPassedBack : Double = 0.0


@IBOutlet weak var dailySavingsNumberLabel: UILabel!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var dailySpendingLimitLabel: UILabel!



override func viewDidLoad() {
    super.viewDidLoad()

    userNameLabel.text = userNamePassedOver
    dailySpendingLimitLabel.text = String(format: "%.2f", userDailyBudgetPassedOver)
    dailySavingsNumberLabel.text = String(format: "%.2f", userDailySavingsPassedOver)

}


@IBAction func addSubtractMoneyPressed(_ sender: UIButton) {

    performSegue(withIdentifier: "addOrSubtractMoney", sender: self)


}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "addOrSubtractMoney"{

        let addOrSubtractMoneyVC = segue.destination as! AddSubtractMoney

            addOrSubtractMoneyVC.dailyBudgetPassedThrough = userDailyBudgetPassedOver
        }
    }

}

extension UserInfoViewController: AddSubtractMoneyDelegate {

func calculatedValue(value: Double) {

    dailySpendingLimitLabel.text = String(userDailyBudgetPassedOver - value)

}

}

import UIKit

protocol AddSubtractMoneyDelegate {
  func calculatedValue(value: Double)
}

class AddSubtractMoney: UIViewController {

@IBOutlet weak var outputLabel: UILabel!

var runningNumber = ""
var finalNumberPassedOver : Double?
var amountPassedBackToUserInfo : Double = 0.0
var dailyBudgetPassedThrough : Double = 0.0

var delegate: AddSubtractMoneyDelegate?

override func viewDidLoad() {
    super.viewDidLoad()

    outputLabel.text = "0"


    // Do any additional setup after loading the view.
}


@IBAction func buttonPressed(_ sender: UIButton) {
    runningNumber += "\(sender.tag)"
    outputLabel.text = runningNumber


}

@IBAction func submitNewInfo(_ sender: UIButton) {

    // FIX FIX

    AddSubtractMoneyController.addToMoneySpentArray(amountISpent: outputLabel.text!)

    sendBackUpdatedNumber()

    dismiss(animated: true, completion: nil)

}


@IBAction func allClearedPressed(_ sender: UIButton) {
    runningNumber = ""
    outputLabel.text = "0"
}

// THIS LINE PRODUCES THE CORRECT INPUT IN OUTPUT CONSOLE WHEN I PRINT- BUT I CANT FIGURE HOW TO TRANSFER IT BACK TO PREVIOUS VC

func sendBackUpdatedNumber(){

    let newestUpdate = UserInfo(whatYouSpentToday: runningNumber, oldDailyBudgetPassed: dailyBudgetPassedThrough)

   amountPassedBackToUserInfo = dailyBudgetPassedThrough - Double(runningNumber)!
   newestUpdate.goalToSaveDaily = amountPassedBackToUserInfo

    print(amountPassedBackToUserInfo)

    self.delegate?.calculatedValue(value: amountPassedBackToUserInfo)


}


}

推荐答案

我的建议是使用回调闭包.与协议/委托相比,它的代码更少,处理起来也更容易.

My suggestion is to use a callback closure. It's less code and easier to handle than protocol / delegate.

AddSubtractMoney中声明一个callback变量,并在sendBackUpdatedNumber中调用它并传递Double

In AddSubtractMoney declare a callback variable and call it in sendBackUpdatedNumber passing the Double value

class AddSubtractMoney: UIViewController {

   // ...

    var callback : ((Double)->())?

  // ...

    func sendBackUpdatedNumber(){

        let newestUpdate = UserInfo(whatYouSpentToday: runningNumber, oldDailyBudgetPassed: dailyBudgetPassedThrough)
        amountPassedBackToUserInfo = dailyBudgetPassedThrough - Double(runningNumber)!
        newestUpdate.goalToSaveDaily = amountPassedBackToUserInfo
        print(amountPassedBackToUserInfo)
        callback?(amountPassedBackToUserInfo)
    }
}

prepare(for segue中,将闭包分配给callback变量,并添加要在返回时执行的代码

In prepare(for segue assign the closure to the callback variable and add the code to be executed on return

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "addOrSubtractMoney"{
        let addOrSubtractMoneyVC = segue.destination as! AddSubtractMoney
        addOrSubtractMoneyVC.callback = { result in
             print(result)
            // do something with the result
        }
        addOrSubtractMoneyVC.dailyBudgetPassedThrough = userDailyBudgetPassedOver
    }
}

这篇关于快速将计算的数据传递回上一个视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆