使用文本字段设置变量的值

时间:2015-01-27 03:00:42

标签: objective-c cocoa xcode4 nstextfield

我的XIB中有几个NSTextField。我为我的一个文本字段创建了操作,它看起来像

- (IBAction)setXPos:(id)sender;

在我的AppDelegate.h文件中,我还创建了一个名为int的{​​{1}}。在我的AppDelegate.m文件中,我无法将XPos的值设置为我在文本字段中键入的内容。这里有什么帮助?我需要做一个

XPos
在我的AppDelegate.h中

?我目前的代码如下:

@property

但它错了。

1 个答案:

答案 0 :(得分:1)

这很简单。在你的.h文件中:

@interface AppDelegate : NSObject <NSApplicationDelegate>

{
    IBOutlet NSTextField *xPosTextBox;
}

- (IBAction)setXPos:(id)sender;

确保将两者都连接到IB中的NSTextField。对于下一步,我假设您在文本框中有一个数字格式化程序,并且xPos是双精度数。在applicationDidFinishLaunching中:

[[xPosTextBox formatter] setFormat:@"##0.000"];
[xPosTextBox setDoubleValue:myInitialValue];

然后在AppDelegate代码中的某处添加一个方法:

- (IBAction)setXPos:(id)sender
{
     xPos = [xPosTextBox doubleValue];
}

容易。

如果你在applicationDidFinishLaunching中有一个浮点数:

[[xPosTextBox formatter] setFormat:@"##0.000"];
[xPosTextBox setFloatValue:myInitialValue];

然后是IBAction方法:

- (IBAction)setXPos:(id)sender
{
     xPos = [xPosTextBox floatValue];
}

如果你有一个int(或NSInteger),不需要数字格式化器,所以在applicationDidFinishLaunching中:

[xPosTextBox setIntValue:myInitialValue];
// [xPosTextBox setIntegerValue:myInitialValue]; for NSInteger

然后是IBAction方法:

- (IBAction)setXPos:(id)sender
{
     xPos = [xPosTextBox intValue];
    // xPos = [xPosTextBox integerValue]; for NSInteger
}