计算背后的一键点击

时间:2018-11-30 09:07:55

标签: swift uitextfield calculation

我正在开发一个相当简单的燃料计算累加器应用程序。该代码需要转换等于或大于1000的所有数字,因此千位数字使用的字体比百位字体大。我已经在这个社区的帮助下成功完成了此任务,谢谢!

但是,当轻按字段并输入数字时,就像按键始终落后一遍,既导致计算不正确,又attributedString函数无法正确显示(即使编码正确) )。在键盘外点击时,最后的笔划显示在字段中,但未在函数中计算出来。因此,例如,输入1在已编辑字段中显示1,但总计仍为0。正确输入另一个1将在编辑的字段中显示11,但总共只显示1(上一个按键)。添加另一个1并在字段外点击可以在第一个字段中显示111,但总共显示11(而应该显示相同的111)。只需点击第二个字段,突然计算出的正确值总计为111,但是在调用该函数时输入更多数字具有相同的“滞后” ...

我看不到代码有什么问题,但我怀疑委托有问题。直到再次敲击键盘才调用这些功能...

func textFieldDidBeginEditing(_ textField: UITextField) {
    if (textField == main1Field) {
        main1Field.text = ""
    } else if (textField == main2Field) {
        main2Field.text = ""
    } else if (textField == centerField) {
        centerField.text = ""
    }
}

//Change font when number input exceeds 3 digits
func getAttributedString(for number: Int) -> NSAttributedString {

    let defaultAttributes = [
        NSAttributedString.Key.font: UIFont(name: "font1", size: 50.0)!
    ]
    let bigNumberAttributes = [
        NSAttributedString.Key.font: UIFont(name: "font2", size: 50.0)!
    ]

    let attributedString = NSMutableAttributedString(string: "\(number)", attributes: defaultAttributes)
    if attributedString.length > 3 {
        let range = NSMakeRange(0, attributedString.length - 3)
        attributedString.setAttributes(bigNumberAttributes, range: range)
    }

    return attributedString
}

//Real-time calculation of entries made to the fields and output it live to the total
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    //Convert the String inserted into the fields into Int and create variables
    let centerFuel = Int(centerField.text!) ?? 0
    let main1Fuel = Int(main1Field.text!) ?? 0
    let main2Fuel = Int(main2Field.text!) ?? 0

    centerField.attributedText = getAttributedString(for: centerFuel)
    main1Field.attributedText = getAttributedString(for: main1Fuel)
    main2Field.attributedText = getAttributedString(for: main2Fuel)

    if centerFuel == 0 && main1Fuel == 0 && main2Fuel == 0 {
        let total = 0
        totalField.attributedText = getAttributedString(for: total)
    } else if (main1Fuel > 0 || main2Fuel > 0) && centerFuel == 0 {
        let total = main1Fuel + main2Fuel
        totalField.attributedText = getAttributedString(for: total)
    } else {
        let total = centerFuel + main1Fuel + main2Fuel
        totalField.attributedText = getAttributedString(for: total)
    }

    return true
}

//Hide keyboard when hitting Return
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

//Hide keyboard when tapping outside of field
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

0 个答案:

没有答案
相关问题