NSTextField に改行文字を入力できないようにしたいのですが、これはデフォルトで Option-Enter (または Option-Return) を入力することで可能です。
Option 修飾子を使用せずに改行を許可する方法を説明しているページをいくつか 見つけましたが、改行を完全に無効にする方法は見つかりませんでした。
これはどのように行うことができますか?
NSFormatter のサブクラスを作成し、 isPartialStringValid:... メソッドを実装して改行をブロックすることができます。
- (BOOL)isPartialStringValid:(NSString **)partialStringPtr
proposedSelectedRange:(NSRangePointer)proposedSelRangePtr
originalString:(NSString *)origString
originalSelectedRange:(NSRange)origSelRange
errorDescription:(NSString **)error
{
// the user may have:
// -- deleted the left most character
// -- deleted the last character and we have an empty string
// both cases are valid
if (proposedSelRangePtr->location == 0)
return YES;
unichar theChar = [*partialStringPtr characterAtIndex:proposedSelRangePtr->location - 1];
if ([[NSCharacterSet newlineCharacterSet] characterIsMember:theChar]) {
*error = nil;
NSBeep();
return NO;
}
return YES;
}
May I ask why you wish to disable this feature? It's a pretty standard part of the OS. Bear in mind that the user might well paste in some string from elsewhere that contains a line break and they'll then edit to their needs. Would it perhaps be better to leave this feature intact, but use an NSFormatter to strip out everything after the line break when it is time to copy the value out of the view to the model?