2

NSTextField に改行文字を入力できないようにしたいのですが、これはデフォルトで Option-Enter (または Option-Return) を入力することで可能です。

Option 修飾子を使用せずに改行を許可する方法を説明しているページをいくつか 見つけましたが、改行を完全に無効にする方法は見つかりませんでした。

これはどのように行うことができますか?

4

3 に答える 3

3

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;
}
于 2009-02-24T03:22:20.833 に答える
0

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?

于 2009-03-01T11:43:16.360 に答える