Restrict NSTextField to only allow numbers

前端 未结 9 1602
[愿得一人]
[愿得一人] 2020-12-23 18:31

How do I restrict a NSTextfield to allow only numbers/integers? I\'ve found questions like this one, but they didn\'t help!

9条回答
  •  半阙折子戏
    2020-12-23 19:07

    Swift 3 Version

    import Foundation
    
        class OnlyIntegerValueFormatter: NumberFormatter {
    
        override func isPartialStringValid(_ partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer?, errorDescription error: AutoreleasingUnsafeMutablePointer?) -> Bool {
    
            // Ability to reset your field (otherwise you can't delete the content)
            // You can check if the field is empty later
            if partialString.isEmpty {
                return true
            }
    
            // Optional: limit input length
            /*
            if partialString.characters.count>3 {
                return false
            }
            */
    
            // Actual check
            return Int(partialString) != nil
        }
    }
    

    Use:

    let onlyIntFormatter = OnlyIntegerValueFormatter()
    myNsTextField.formatter = onlyIntFormatter
    

提交回复
热议问题