How to limit the textfield entry to 2 decimal places in swift 4?

后端 未结 8 1807
逝去的感伤
逝去的感伤 2021-01-02 00:12

I have a textfield and I want to limit the entry to max 2 decimal places.

number like 12.34 is allowed but not 12.345

How do I do it?

8条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-02 00:50

    In Swift 4.

    TextField have 10 digit limit and after decimal 2 digit limit (you can change the Limits). The dot will allow only one time in the textField.

    class ViewController: UIViewController,UITextFieldDelegate {
    
        var dotLocation = Int()
    
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
    
            let nonNumberSet = CharacterSet(charactersIn: "0123456789.").inverted
    
            if Int(range.length) == 0 && string.count == 0 {
                return true
            }
    
            if (string == ".") {
                if Int(range.location) == 0 {
                    return false
                }
                if dotLocation == 0 {
                    dotLocation = range.location
                    return true
                } else {
                    return false
                }
            }
    
            if range.location == dotLocation && string.count == 0 {
                dotLocation = 0
            }
    
            if dotLocation > 0 && range.location > dotLocation + 2 {
                return false
            }
    
            if range.location >= 10 {
    
                if dotLocation >= 10 || string.count == 0 {
                    return true
                } else if range.location > dotLocation + 2 {
                    return false
                }
    
                var newValue = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
                newValue = newValue?.components(separatedBy: nonNumberSet).joined(separator: "")
                textField.text = newValue
    
                return false
    
            } else {
                return true
            }
    
        }
    
    }
    

提交回复
热议问题