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

时间:2012-12-27 05:41:59

标签: objective-c cocoa cocoa-bindings nstextfield

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

当我输入文本字段时,它不会更新变量。它一直等到我按下Enter键。我不想每次都按Enter键。

为了立即修改绑定更改值,我需要更改什么?

2 个答案:

答案 0 :(得分:4)

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

NSTextField Value binding with Continuously Updates Value checked.


然而,通常,您真正想要做的是更新用户完成编辑并按下按钮时文本字段绑定到的属性(“保存”或“确定” , 例如)。为此,您无需如上所述不断更新属性,只需要结束编辑即可。 Daniel Jalkut provides an extremely useful implementation of just such a method

@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...
}

答案 1 :(得分:0)

之前的答案很漂亮,我从中学到了如何欺骗窗口/视图/文档系统来对程序员的所有内容进行最终编辑。

然而,默认的响应者链行为(包括保留第一个响应者,直到USER将他们的注意力转移到其他地方)是Mac的基本外观和感觉"我不会轻易搞砸它(我发誓我在响应链操作中做了非常强大的事情,所以我不会出于恐惧而说出来。)

此外 - 甚至还有一种更简单的方法 - 不需要更改绑定。在Interface-builder中,选择文本字段,然后选择" Attribute Inspector"标签。您将看到以下内容: Interface-Builder Attribute-inspector tab

检查红圈"连续"会做的。这个选项是基本的,甚至比绑定更旧,它的主要用途是允许验证器对象(一个全新的故事)验证文本并在用户输入时动态更改它。当text-field调用验证器调用时,它还会更新绑定值。

相关问题