dagronf / DSFStepperView

A custom stepper text field for macOS and iOS, supporting Swift, Objective-C, SwiftUI and Catalyst
MIT License
63 stars 7 forks source link

Suggestion for check input for macOS (only number) #3

Open DevulderJeanPaul opened 3 years ago

DevulderJeanPaul commented 3 years ago

Hi,

I have add a simple function for check input on the NSTextField (macOS only)

Add this extension

extension String {
func isNumber() -> Bool {
    return !self.isEmpty && self.rangeOfCharacter(from: CharacterSet.decimalDigits) != nil && self.rangeOfCharacter(from: CharacterSet.letters) == nil
}}

Add this code on the stepper view class

func
_evt(_ e:NSEvent) -> NSEvent?
{
    if e.type == .keyDown
    {
        if let s = e.characters
        {
            if s.rangeOfCharacter(from: CharacterSet.alphanumerics) == nil
            {
                return e
            }

            if s.isNumber()
            {
                return e
            }

            return nil
        }
    }

    return e
}

public func
use_filter()
{
    NSEvent.addLocalMonitorForEvents(matching: [.keyDown], handler: _evt)
}

Call method use_filter()

mystepper1. use_filter()

Now you can hit only number in NSTextField (alphanumbers are correct check but if you hit "%" doesn't work!)

May be is utile for you in future version ?

dagronf commented 3 years ago

Ah that's a really good point mate -- I'd not thought about filtering the input field (rather just going 'beep' when the edited field is not a number!). Thank you for the idea and the code sample - I'll need to think about how to handle fractional values and locales too (ie. 10.5 here in Australia is 10,5 in Germany so its not as simple as a check for .) as the control can step by fractional values too, but its a really solid idea.

Thanks!