NSTextField持续更新



我不知道如何让NSTextfield自动更新,而不必按"返回"或单击另一个文本字段。

我的目标是在一个字段中输入一个数字,并让其他字段同时更新。我试着在文本字段属性中点击"连续",但它似乎没有做任何事情。

这是我的接口文件:

#import <Foundation/Foundation.h>
@interface InchController : NSObject {
    IBOutlet NSTextField *centimetersTextField;
    IBOutlet NSTextField *inchesTextField;
    IBOutlet NSTextField *feetTextField;
}
-(IBAction)convert:(id)sender;
@end
这是我的实现文件:
#import "InchController.h"
@implementation InchController
- (IBAction)convert:(id)sender {
    if (sender == inchesTextField) {
        float inches = [inchesTextField floatValue];
        [feetTextField setFloatValue:(inches * 0.0833)];
        [centimetersTextField setFloatValue:(inches * 2.54)];
    }
    else if (sender == feetTextField) {
        float feet = [feetTextField floatValue];
        [inchesTextField setFloatValue:(feet * 12)];
        [centimetersTextField setFloatValue:(feet * 30.48)];
    }
    else if (sender == centimetersTextField) {
        float centimeters = [centimetersTextField floatValue];
        [inchesTextField setFloatValue:(centimeters * 0.394)];
        [feetTextField setFloatValue:(centimeters * 0.033)];
    }
}
@end

所以这是根据Josh的解决方案更新的实现文件。注释掉IBAction,因为在实现和接口文件中不再需要它。

#import "LengthController.h"
@implementation LengthController
//- (IBAction) convert: (id)sender {
//}
-(void) controlTextDidChange:(NSNotification *) note {
    NSTextField *changedField = [note object];
    if (changedField == inchesTextField) {
        float inches = [inchesTextField floatValue];
        [feetTextField setFloatValue: (inches * 0.0833)];
        [centimetersTextField setFloatValue: (inches * 2.54)];
    }
    if (changedField == centimetersTextField) {
        float centimeters = [centimetersTextField floatValue];
        [inchesTextField setFloatValue:(centimeters * 0.394)];
        [feetTextField setFloatValue:(centimeters * 0.033)];
    }
    if (changedField == feetTextField) {
        float feet = [feetTextField floatValue];
        [inchesTextField setFloatValue:(feet * 12)];
        [centimetersTextField setFloatValue:(feet * 30.48)];
    }
}
@end

让你的控制器成为文本域的委托;您可以在Interface Builder中通过按ctrl从文本字段拖动到控制器来设置它。

在你的控制器中,实现"NSControl Delegate"方法controlTextDidChange:,当字段的文本发生变化时,它将被调用(顾名思义)。在该方法中,您可以验证文本,如果合适的话,还可以更新其他字段的内容。

传入的参数可以给你改变的文本字段;然后,您可以将其传递给现有的convert:方法以重用代码:

- (void) controlTextDidChange: (NSNotification *)note {
    NSTextField * changedField = [note object];
    [self convert:changedField];
}

动作方法没有什么特别的。IBAction返回类型计算结果为void;它只被Xcode用来暴露Interface Builder中使用的方法。因此,您可以像调用其他方法一样调用它们。在这里,您获得适当的字段并将其作为sender参数传递进来,就好像该字段调用了操作方法本身一样。

根据问题的复杂程度,绑定也可能是一种可行的解决方案。

您可以在模型或模型控制器对象上定义属性,并将它们连接到相应的文本字段。然后,文本字段中的更改立即反映在属性中,然后可以触发对其他属性的更改。

绑定到这些"派生"属性的文本字段将自动更新。

记得用willChangeValueForKey:didChangeValueForKey:"括号"括住你对派生属性的更改,这样更改就会发送给观察者。更多。

当然,如果你在依赖项中有循环,它会变得很难看;在这种情况下,其他答案中提到的controlTextDidChange:方法可能更好。

最新更新