如何限制NSTextField文本长度并保持它总是大写? [英] How to limit NSTextField text length and keep it always upper case?
问题描述
需要一个NSTextField,文本限制最多为4个字符,并且始终以大写形式显示,但无法找出实现这一点的好方法。我试图通过一个验证方法的绑定,但验证只有当控制失去第一响应者,这是不好的时候被调用。
Need to have an NSTextField with a text limit of 4 characters maximum and show always in upper case but can't figure out a good way of achieving that. I've tried to do it through a binding with a validation method but the validation only gets called when the control loses first responder and that's no good.
Temporarly我做了工作通过观察通知NSControlTextDidChangeNotification在文本字段并让它调用方法:
Temporarly I made it work by observing the notification NSControlTextDidChangeNotification on the text field and having it call the method:
- (void)textDidChange:(NSNotification*)notification {
NSTextField* textField = [notification object];
NSString* value = [textField stringValue];
if ([value length] > 4) {
[textField setStringValue:[[value uppercaseString] substringWithRange:NSMakeRange(0, 4)]];
} else {
[textField setStringValue:[value uppercaseString]];
}
}
但这肯定不是最好的做法它。任何更好的建议?
But this surely isn't the best way of doing it. Any better suggestion?
推荐答案
我做Graham Lee建议和它的工作正常,这里是自定义格式化程序代码:
I did as Graham Lee suggested and it works fine, here's the custom formatter code:
UPDATED:添加了Dave Gallagher报告的修复程序。谢谢!
UPDATED: Added fix reported by Dave Gallagher. Thanks!
@interface CustomTextFieldFormatter : NSFormatter {
int maxLength;
}
- (void)setMaximumLength:(int)len;
- (int)maximumLength;
@end
@implementation CustomTextFieldFormatter
- (id)init {
if(self = [super init]){
maxLength = INT_MAX;
}
return self;
}
- (void)setMaximumLength:(int)len {
maxLength = len;
}
- (int)maximumLength {
return maxLength;
}
- (NSString *)stringForObjectValue:(id)object {
return (NSString *)object;
}
- (BOOL)getObjectValue:(id *)object forString:(NSString *)string errorDescription:(NSString **)error {
*object = string;
return YES;
}
- (BOOL)isPartialStringValid:(NSString **)partialStringPtr
proposedSelectedRange:(NSRangePointer)proposedSelRangePtr
originalString:(NSString *)origString
originalSelectedRange:(NSRange)origSelRange
errorDescription:(NSString **)error {
if ([*partialStringPtr length] > maxLength) {
return NO;
}
if (![*partialStringPtr isEqual:[*partialStringPtr uppercaseString]]) {
*partialStringPtr = [*partialStringPtr uppercaseString];
return NO;
}
return YES;
}
- (NSAttributedString *)attributedStringForObjectValue:(id)anObject withDefaultAttributes:(NSDictionary *)attributes {
return nil;
}
@end
这篇关于如何限制NSTextField文本长度并保持它总是大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!