将限制设置为NSTextField [英] Set limit to NSTextField
本文介绍了将限制设置为NSTextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要为TextFields设置一个字符限制.我遵循了此 answer ,并且可以设置一个限制.但是现在当我按Enter键时,所有字符都消失了.出了什么问题?
I need to set a character limit for TextFields. I followed this answer and I was able to set a limit. But now when I press enter all characters are wiped out. What went wrong ?
- (BOOL)isPartialStringValid:(NSString *__autoreleasing *)partialStringPtr
proposedSelectedRange:(NSRangePointer)proposedSelRangePtr
originalString:(NSString *)origString
originalSelectedRange:(NSRange)origSelRange
errorDescription:(NSString *__autoreleasing *)error {
if ([*partialStringPtr length] > maxLength)
return NO;
else
return YES;
}
- (NSString *)stringForObjectValue:(id)obj {
return (NSString*) obj;
}
- (BOOL)getObjectValue:(out __autoreleasing id *)obj
forString:(NSString *)string
errorDescription:(out NSString *__autoreleasing *)error {
return YES;
}
- (NSAttributedString *)attributedStringForObjectValue:(id)obj
withDefaultAttributes:(NSDictionary *)attrs {
return (NSAttributedString*) obj;
}
推荐答案
如何将自己设置为NSTextField的委托并实现此委托方法?
How about setting yourself as delegate of the NSTextField an implement this delegate method?
- (void)textDidChange:(NSNotification *)aNotification
在这种情况下,您可以检查文本是否太长,然后将其剪切.
There you could check if the text is too long and then cut it if this is the case.
NSTextField *textField = (NSTextField *)[aNotification object];
if ([textField.stringValue length] > maxLength)
{
textField.stringValue = [textField.stringValue substringWithRange:NSMakeRange(0,maxLength)];
}
这篇关于将限制设置为NSTextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文