Restrict NSTextField to only allow numbers

前端 未结 9 1601
[愿得一人]
[愿得一人] 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 18:59

    [Works with Swift 3.0.1]

    As others suggested, subclass NumberFormatter and override isPartialStringValid method. The easiest way is to drop a NumberFormatter object under your NSTextField in xib/storyboard and update it's Custom Class. Next implementation allows only integers or blank value and plays a beep if string contains illegal characters.

    class IntegerFormatter: NumberFormatter {
    
        override func isPartialStringValid(_ partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer?, errorDescription error: AutoreleasingUnsafeMutablePointer?) -> Bool {
    
            // Allow blank value
            if partialString.numberOfCharacters() == 0  {
                return true
            }
    
            // Validate string if it's an int
            if partialString.isInt() {
                return true
            } else {
                NSBeep()
                return false
            }
        }
    }
    

    String's numberOfCharacters() and isInt() are methods added in an extension.

    extension String {
    
        func isInt() -> Bool {
    
            if let intValue = Int(self) {
    
                if intValue >= 0 {
                    return true
                }
            }
    
            return false
        }
    
        func numberOfCharacters() -> Int {
            return self.characters.count
        }
    }
    

提交回复
热议问题