如何限制 NSTextField 文本长度并保持大写? [英] How to limit NSTextField text length and keep it always upper case?
问题描述
需要有一个文本限制为最多 4 个字符的 NSTextField 并始终以大写显示,但无法找到实现这一目标的好方法.我尝试通过与验证方法的绑定来完成此操作,但仅在控件丢失第一响应者时才调用验证,这不好.
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.
暂时我通过观察文本字段上的通知 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:
更新:添加了 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屋!