Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
DevulderJeanPaul opened this issue Sep 5, 2021 · 1 comment
Open

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

DevulderJeanPaul opened this issue Sep 5, 2021 · 1 comment

Comments

@DevulderJeanPaul
Copy link

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
Copy link
Owner

dagronf commented Sep 5, 2021

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants