gpt4 book ai didi

objective-c - 更新从文本字段绑定(bind)的属性,无需按 Enter 键

转载 作者:行者123 更新时间:2023-12-03 16:54:47 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

NSTextField Value binding with Continuously Updates Value checked.


但是,大​​多数情况下,您真正​​想要做的是当用户完成编辑并按下按钮(“保存”或“确定”)时更新文本字段绑定(bind)的属性, 例如)。为此,您无需如上所述不断更新属性,只需结束编辑即可。 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

因此,如果您有一个针对 View Controller 的方法 -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...
}

关于objective-c - 更新从文本字段绑定(bind)的属性,无需按 Enter 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14049913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com