Restrict NSTextField to only allow numbers

前端 未结 9 1589
[愿得一人]
[愿得一人] 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条回答
  •  梦毁少年i
    2020-12-23 18:51

    Swift 2.0 custom formatter with 0 instead of empty space :

    class OnlyIntegerValueFormatter: NSNumberFormatter {
    
        override func isPartialStringValid(partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer, errorDescription error: AutoreleasingUnsafeMutablePointer) -> Bool {
    
            if partialString.isEmpty {
                newString.memory = "0"
                return false
            }
    
            if Int(partialString) < 0 {
                NSBeep()
                return false
            } else {
                return true
            }
        }
    }
    

提交回复
热议问题