UITextField 輸入小數

· 2min
Table of Contents

前言

如何檢測 UITextField 輸入小數.

實作

  1. 設置 textField.keyboardType = .decimalPad
  2. 設置 textField.delegate = ...
  3. 處理 delegate functions shouldChangeCharactersIn
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    guard let text = textField.text else {
        return true
    }

    /// 1.过滤删除事件
    guard !string.isEmpty else {
        return true
    }

    /// 2.检查允许输入的合法字符
    guard "0123456789.".contains(string) else {
        return false
    }

    /// 3.检查总长度限制 (最多输入10位)
    if text.count >= 10 {
        return false
    }

    /// 4.检查小数点后位数限制 (小数点后最多输入2位)
    if let ran = text.range(of: "."), range.location - NSRange(ran, in: text).location > 2 {
        return false
    }

    /// 5.检查首位输入是否为0
    if text == "0", string != "." {
        textField.text = string
        return false
    }

    /// 6.特殊情况检查
    guard string == "." || string == "0" else {
           return true
       }

    /// a.首位小数点替换为0.
    if text.count == 0, string == "." {
        textField.text = "0."
        return false
    }

    /// b.禁止多次输入小数点
    if text.range(of: ".") != nil, string == "." {
        return false
    }

    return true
}

參考

UITextField金额输入、小数点处理、输入位数限制等