Restrict NSTextField input to numeric only? NSNumberformatter

后端 未结 5 1550
心在旅途
心在旅途 2020-12-06 02:44

I\'m just getting started up with Mac App Development and so far everything is good well, I\'m just having problems trying to get a NSTextField to only accept numbers for th

5条回答
  •  离开以前
    2020-12-06 03:06

    Rather than subclassing anything, you can do it with an NSControlTextEditingDelegate method in your view controller. Set the delegate field of the NSTextField you want to check and then do something like the following in a controlTextDidChange: function which gets called on each character typed. Don't forget to initialize self.lastValidTimestampCount in this case. This function uses RegExLite to check the value, which may include commas.

    // Make sure the user has typed a valid number so far.
    - (void)controlTextDidChange:(NSNotification *)obj
    {
        if (obj.object == self.timestampsCount)
        {
            NSString *countValue = timestampsCount.stringValue;
            if (! [countValue isMatchedByRegex:@"^[\\d\\,]{1,6}$"])
            {
                timestampsCount.stringValue = self.lastValidTimestampCount;
                NSBeep();
            }
            else
                self.lastValidTimestampCount = timestampsCount.stringValue;
        }
    }
    

提交回复
热议问题