Difference between revisions of "Snippets"
Jump to navigation
Jump to search
Line 15: | Line 15: | ||
4. Then you are free to examinate the conditions... | 4. Then you are free to examinate the conditions... | ||
− | --[[ | + | == Limiting text input length in ''NSTextField'' == |
+ | (based on Alexander Malmberg's snippet) | ||
+ | |||
+ | 1. Subclass NSTextField | ||
+ | |||
+ | 2. In your subclass adopt the | ||
+ | - (BOOL) textView: (NSTextView*) textView | ||
+ | shouldChangeTextInRange: (NSRange) range | ||
+ | replacementString: (NSString*) replacementString | ||
+ | method. | ||
+ | |||
+ | 3. Create an instance variable setting method: | ||
+ | - (void) setMaxLength: (int) ml | ||
+ | { | ||
+ | maxLength = ml; | ||
+ | } | ||
+ | |||
+ | 4. Then fill your method 2. with this: | ||
+ | int newLength; | ||
+ | /* The exact change isn't known. Disallow the change to be safe. */ | ||
+ | if (range.location == NSNotFound) | ||
+ | return NO; | ||
+ | newLength=[[textView textStorage] length]+[replacementString length]-r.length; | ||
+ | if (newLength>maxLength) | ||
+ | return YES; //allowing | ||
+ | else | ||
+ | return NO; // not allowing |
Revision as of 11:35, 26 June 2005
Testing chars entered by users in NSTextField
(just for the case if someone else has the same problem)
1. Subclass NSTextField
2. In your subclass adopt the
- (BOOL) textView: (NSTextView*) textView shouldChangeTextInRange: (NSRange) range replacementString: (NSString*) replacementString
method.
3. In this method you can access to the replacementString as char with the following line:
char c = *([replacementString cString) + 0];
4. Then you are free to examinate the conditions...
Limiting text input length in NSTextField
(based on Alexander Malmberg's snippet)
1. Subclass NSTextField
2. In your subclass adopt the
- (BOOL) textView: (NSTextView*) textView shouldChangeTextInRange: (NSRange) range replacementString: (NSString*) replacementString
method.
3. Create an instance variable setting method:
- (void) setMaxLength: (int) ml { maxLength = ml; }
4. Then fill your method 2. with this:
int newLength; /* The exact change isn't known. Disallow the change to be safe. */ if (range.location == NSNotFound) return NO; newLength=[[textView textStorage] length]+[replacementString length]-r.length; if (newLength>maxLength) return YES; //allowing else return NO; // not allowing