更新从文本字段绑定的属性,无需按 Enter 键

2024-04-05

我有一个文本字段,并将其绑定到NSString实例变量。

当我在文本字段中键入内容时,它不会更新变量。它会等到我按下 Enter 键。我不想每次都按 Enter 键。

我需要更改什么才能立即更改绑定值?


默认情况下,a 的值绑定NSTextField不持续更新。要解决此问题,您需要在选择文本字段后,选中“值”标题下的“绑定检查器”中的“连续更新值”框:


However大多数情况下,您真正​​想要做的是当用户完成编辑并按下按钮(例如“保存”或“确定”)时更新文本字段绑定的属性。为此,您无需如上所述不断更新属性,只需结束编辑即可。Daniel Jalkut 提供了这种方法的极其有用的实现 http://www.red-sweater.com/blog/229/stay-responsive:

@interface NSWindow (Editing)

- (void)endEditing;

@end

@implementation NSWindow (Editing)

- (void)endEditing
{
    // Save the current first responder, respecting the fact
    // that it might conceptually be the delegate of the 
    // field editor that is "first responder."
    id oldFirstResponder = [oMainDocumentWindow firstResponder];
    if ((oldFirstResponder != nil) &&
        [oldFirstResponder isKindOfClass:[NSTextView class]] &&
        [(NSTextView*)oldFirstResponder isFieldEditor])
    {   
        // A field editor's delegate is the view we're editing
        oldFirstResponder = [oldFirstResponder delegate];
        if ([oldFirstResponder isKindOfClass:[NSResponder class]] == NO)
        {
            // Eh ... we'd better back off if 
            // this thing isn't a responder at all
            oldFirstResponder = nil;
        }
    } 

    // Gracefully end all editing in our window (from Erik Buck).
    // This will cause the user's changes to be committed.
    if([oMainDocumentWindow makeFirstResponder:oMainDocumentWindow])
    {
        // All editing is now ended and delegate messages sent etc.
    }
    else
    {
        // For some reason the text object being edited will
        // not resign first responder status so force an 
        /// end to editing anyway
        [oMainDocumentWindow endEditingFor:nil];
    }

    // If we had a first responder before, restore it
    if (oldFirstResponder != nil)
    {
        [oMainDocumentWindow makeFirstResponder:oldFirstResponder];
    }
}

@end

因此,如果您有一个针对视图控制器方法的“保存”按钮-save:,你会打电话给

- (IBAction)save:(id)sender
{
    [[[self view] window] endEditing];
    //at this point, all properties bound to text fields have the same
    //value as the contents of the text fields.

    //save stuff...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

更新从文本字段绑定的属性,无需按 Enter 键 的相关文章

随机推荐