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

后端 未结 8 1836
逝去的感伤
逝去的感伤 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:46

    None of the answers handled the decimalSeparator and all the edge cases I came across so I decided to write my own.

    extension YourController: UITextFieldDelegate {
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            guard let text = textField.text, let decimalSeparator = NSLocale.current.decimalSeparator else {
                return true
            }
    
             var splitText = text.components(separatedBy: decimalSeparator)
             let totalDecimalSeparators = splitText.count - 1
             let isEditingEnd = (text.count - 3) < range.lowerBound
    
             splitText.removeFirst()
    
             // Check if we will exceed 2 dp
             if
                 splitText.last?.count ?? 0 > 1 && string.count != 0 &&
                 isEditingEnd
             {
                 return false
             }
    
             // If there is already a dot we don't want to allow further dots
             if totalDecimalSeparators > 0 && string == decimalSeparator {
                 return false
             }
    
             // Only allow numbers and decimal separator
             switch(string) {
             case "", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", decimalSeparator:
                 return true
             default:
                 return false
             }
         }
     }
    

提交回复
热议问题