添加Double和一个字符串,然后显示在UILabel上

时间:2019-01-28 21:55:05

标签: ios swift uilabel

我试图将在文本字段中输入的值与指定为双精度值的值相加,然后在标签上返回该值。我拥有的代码是:

@IBOutlet weak var enterField: UITextField!

var weekOneTotal:Double = 0

 @IBAction func addButton(_ sender: Any) {
        addCorrectValue()

    }

func addCorrectValue () {
        guard let addAmount = convertAmount(input: enterField.text!) else {
            print("Invalid amount")
            return
        }

      let newValue = weekOneTotal += addAmount

        secondScreen.weekOneAmountLabel.text = String(newValue)

}

  func convertAmount (input:String) -> Double? {

        let numberFormatter = NumberFormatter ()
        numberFormatter.numberStyle = .decimal

        return numberFormatter.number(from: input)?.doubleValue
    }

2 个答案:

答案 0 :(得分:1)

尝试一下:

func addCorrectValue () {
    guard let addAmount = Double(enterField.text!) else {
        print("Invalid amount")
        return
    }

    let newValue = weekOneTotal + addAmount

    secondScreen.weekOneAmountLabel.text = "\(String(format: "%.1f", newValue))"
}

.1是显示的小数位数。您可以根据需要进行调整。希望我理解了这个问题,对您有用!

答案 1 :(得分:0)

您可能希望将weekOneTotal变量的值增加转换后的数量,然后再将此值用作某些标签的text

weekOneTotal += addAmount
secondScreen.weekOneAmountLabel.text = String(weekOneTotal)