禁用/启用NSButton如果NSTextfield为空或不是 [英] Disable/Enable NSButton if NSTextfield is empty or not
问题描述
我是可可新手。我有一个按钮和一个textField在我的应用程序。我想要在文本框为空时禁用按钮,并在用户输入内容时启用。
I´m newbie with cocoa. I have a button and a textField in my app. I want the button disabled when the textfield is empty and enabled when the user type something.
任何时候开始?在界面生成器中的任何魔法绑定?
Any point to start? Any "magic" binding in Interface Builder?
感谢
我试图将appDelegate设置为NSTextfield的委托并添加这个方法(myTextfield和myButton是IBOutlets):
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];
}
}
但没有任何反应...
But nothing happens...
推荐答案
我试图将appDelegate设置为NSTextfield的委托,并添加了这个方法(myTextfield和myButton IBOutlets):
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];
}
}
方式,但它应该工作很好。您没有将文本字段的 delegate
outlet连接到此对象,您尚未连接 myTextField
或者您尚未将 myButton
插座连接到该按钮。
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.
其他方法是给控制器一个暴露字符串值的属性,将文本字段的值绑定到此
stringValue
属性,并将按钮的启用
绑定到控制器的 stringValue.length
。
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
.
你还可以给控制器两个属性,一个有一个布尔值,并设置一个依赖于string属性,并绑定按钮。这是一个更清洁和可能更强大的解决方案,虽然它是更多的工作。
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.
这篇关于禁用/启用NSButton如果NSTextfield为空或不是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!