当按下6,7,8,9并限制编辑时,UITextfield值增加增量

时间:2019-02-24 15:33:10

标签: swift uitextfield

UITextField响应不正确。我无法删除当前值,但是当我按键盘上的数字6,7,8,9时,该值将更改。使用UITextfield委托设置此文本字段的方法。当我屏蔽了shouldChangeCharactersIn下的代码部分时,它可以工作。我的问题是为什么代码限制文本字段输入,并且仅在键盘上按下某些数字时才响应?

func textFieldDidEndEditing(_ textField: UITextField) {
    let selectedLender = mortgageLender.text
    let selectedTerm = mortgageTerm.text


        let matchedLender = Data.currentRateData.first(where: {$0.financialInstitution == selectedLender})

        let sixMonthRate = matchedLender?.sixMonths
        let oneYearRate = matchedLender?.oneYear
        let twoYearRate = matchedLender?.twoYear
        let threeYearRate = matchedLender?.threeYear
        let fourYearRate = matchedLender?.fourYear
        let fiveYearRate = matchedLender?.fiveYear

        DispatchQueue.main.async {

        var selectedRateString:String = "0"

        if selectedTerm == "sixMonths" {
            let selectedRate = sixMonthRate
            selectedRateString = selectedRate ?? "0"
        } else if selectedTerm == "1 Year" {
            let selectedRate = oneYearRate
            selectedRateString = selectedRate ?? "0"
        } else if selectedTerm == "2 Year"{
            let selectedRate = twoYearRate
            selectedRateString = selectedRate ?? "0"
        } else if selectedTerm == "3 Year" {
            let selectedRate = threeYearRate
            selectedRateString = selectedRate ?? "0"
        }else if selectedTerm == "4 Year" {
            let selectedRate = fourYearRate
            selectedRateString = selectedRate ?? "0"
        }else if selectedTerm == "5 Year" {
            let selectedRate = fiveYearRate
            selectedRateString = selectedRate ?? "0"
        }

         self.mortgageInterestRate.text = selectedRateString.percentage
    }
    func textField(_ textField: UITextField, shouldChangeCharactersIn 
    range: NSRange, replacementString string: String) -> Bool {


    if textField.text == mortgageInterestRate.text {

        let text: NSString = (textField.text ?? "") as NSString
        let finalString = text.replacingCharacters(in: range, with: 
        string)
        mortgageInterestRate.text = finalString.percentage

        return false

    }
}

    var percentage: String {
    // removing all characters from string before formatting
    let stringWithoutSymbol = self.replacingOccurrences(of: "%", with: 
     "")

    let styler = NumberFormatter()
    styler.minimumFractionDigits = 2
    styler.maximumFractionDigits = 2
    styler.numberStyle = .percent
    styler.multiplier = 1

    if let result = NumberFormatter().number(from: stringWithoutSymbol) 
 {
        return styler.string(from: result)!
    }

    return self
}

0 个答案:

没有答案