12

我是可可的新手。我的应用程序中有一个按钮和一个 textField。我希望在文本字段为空时禁用该按钮,并在用户键入内容时启用该按钮。

有什么要开始的吗?Interface Builder中的任何“魔术”绑定?

谢谢

[编辑]

我尝试将 appDelegate 设置为 NSTextfield 的委托并添加了此方法(myTextfield 和 myButton 是 IBOutlets):

- (void)textDidChange:(NSNotification *)aNotification
{
    if ([[myTextField stringValue]length]>0) {
        [myButton setEnabled: YES];
    }
    else {
        [myButton setEnabled: NO];
    }
}

但是什么也没有发生...

4

4 回答 4

15

I´ve tried to set the appDelegate as the NSTextfield´s delegate and added this method (myTextfield and myButton are IBOutlets):

- (void)textDidChange:(NSNotification *)aNotification
{
    if ([[myTextField stringValue]length]>0) {
        [myButton setEnabled: YES];
    }
    else {
        [myButton setEnabled: NO];
    }
}

That's the hard way, but it should work just fine. Either you haven't hooked up the text field's delegate outlet to this object, you haven't hooked up the myTextField outlet to the text field, or you haven't hooked up the myButton outlet to the button.

The other way would be to give the controller a property exposing the string value, bind the text field's value binding to this stringValue property, and bind the button's enabled binding to the controller's stringValue.length.

You could also give the controller two properties, one having a Boolean value, and set that one up as dependent upon the string property, and bind the button to that. That's a cleaner and possibly more robust solution, though it is more work.

于 2010-09-16T16:06:17.080 回答
10

这是使用绑定的解决方案。

下面我设置了一个绑定到文件所有者的“文本”属性的 NSTextField。“文本”是一个 NSString。我被“不断更新价值”抓住了。认为我的解决方案不起作用,但实际上它并没有随着用户键入而更新,并且只有在文本字段失去焦点时才会更新。

将 NSTextField 绑定到文件的所有者 NSString 文本属性

现在在按钮上设置绑定,只需将其启用状态设置为文件所有者的文本属性的长度。

将 NSButton 的启用状态绑定到文本属性的长度

而且,工作产品。

在此处输入图像描述 在此处输入图像描述

于 2014-06-03T14:36:16.267 回答
4

如果你使用 controlTextDidChange 而不是 textDidChange,你可以摆脱通知的东西,只依靠成为 NSTextField 的代表。

于 2011-05-28T06:24:24.997 回答
0

谢谢彼得。我错过了(在我的艰难版本中)是 appDelegate 的 awakeFromNib 中的这段代码:

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(textDidChange:) name:NSControlTextDidChangeNotification object:myTextField];

它工作完美。现在我正在尝试简单的方法,但恐怕我对绑定还不够好。

绑定属性

@property (retain) IBOutlet NSString *aStringValue;

使用文本字段的值,我必须在 IB 中为“绑定到:”、“控制器键”和“模型键路径”使用什么?

于 2010-09-17T14:19:45.967 回答