Question

Is there a way to force capitals in a NSTextField?

I want to create a text field for typing in Post Codes, and I want all post codes entered to use capital letters.

e.g. N1 3ET instead of: n1 3et

Also, I am using a regular expression, which only accepts capitals (I know very little about regular expressions, so I'm not keen on modifying it)

Thank you!

Michael

Was it helpful?

Solution

You could give the NSTextField a delegate with something along the lines of:

- (void)controlTextDidChange:(NSNotification *)aNotification{
    NSText *fieldEditor = [[aNotification userInfo] objectForKey:@"NSFieldEditor"];
    [fieldEditor setString:[[fieldEditor string] uppercaseString]];
}

It should catch text changing notifications and uppercase the text.

OTHER TIPS

Anq's answer works well, but in the Cocoa world, this is what NSFormatter was created for. It's about the same amount of work and can be easily ported to any part of your project (or to any other project).

See also the Data Formatting Programming Guide For Cocoa.

Swift solution. The class that is the NSTextField delegate should contain:

override func controlTextDidChange(obj: NSNotification) 
{
    if let info = obj.userInfo, text = info["NSFieldEditor"] as? NSText,
        string = text.string
    {
        text.string = string.uppercaseString
    }
}

Here is how to do the same thing as Anq's answer in Swift

override func controlTextDidChange(obj: NSNotification!) {
    //Make the username all caps to match the PM
    var infoDictionary:Dictionary = obj.userInfo! as Dictionary
    var text:NSText = infoDictionary["NSFieldEditor"] as NSText;
    text.string = text.string.uppercaseString
}

Hook NStexfield to delegate in IB than:

- (void)controlTextDidChange:(NSNotification *)aNotification{
  editField = [aNotification object];
  NSString* value = [editField stringValue];
  [editField setStringValue:[value uppercaseString]];
  //NSLog(@"editField%@", editField.stringValue);

}

The problem I had with the solutions above is that when I made a change to the textfield in the UI, the cursor would move to the end of the string. So if I had a string in the textfield, like this

[VCOUVER ]

I would place my cursor at 1:

[V|COUVER ]

and type the lower case letter 'a', this would happen:

[VACOUVER| ]

not noticing this, I would type the 'n' and get:

[VACOUVERN| ]

crap... OK, here's my fix:

-(void)controlTextDidChange:(NSNotification *)obj {
    if([obj.object isEqualTo:self.locationTextField]) {
        NSText *fieldEditor = [[obj userInfo] objectForKey:@"NSFieldEditor"];
        NSRange rng = [fieldEditor selectedRange];
        [fieldEditor setString:[[fieldEditor string] uppercaseString]];
        [fieldEditor setSelectedRange:rng];
    }
}

That is, before applying the uppercase, grab the position of the cursor, apply the uppercase, and then put the cursor back.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top