我的 XIB 中有一些 NSTextField。我为我的一个文本字段创建了操作,它看起来像
- (IBAction)setXPos:(id)sender;
在我的 AppDelegate.h 文件中,我还创建了一个名为 XPos
的 int
。在我的 AppDelegate.m 文件中,我无法将 XPos 的值设置为我在文本字段中输入的值。这里有什么帮助吗?我需要做吗
@property
在我的 AppDelegate.h 中?我当前的代码如下所示:
XPos = sender;
但它出错了。
最佳答案
这很简单。在您的 .h 文件中:
@interface AppDelegate : NSObject <NSApplicationDelegate>
{
IBOutlet NSTextField *xPosTextBox;
}
- (IBAction)setXPos:(id)sender;
确保将两者连接到 IB 中的 NSTextField。对于下一步,我假设文本框中有一个数字格式化程序,并且 xPos 是 double 值。在 applicationDidFinishLaunching 中:
[[xPosTextBox formatter] setFormat:@"##0.000"];
[xPosTextBox setDoubleValue:myInitialValue];
然后在 AppDelegate 代码中的某个位置添加一个方法:
- (IBAction)setXPos:(id)sender
{
xPos = [xPosTextBox doubleValue];
}
简单。
如果 applicationDidFinishLaunching 中有一个 float :
[[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
}
关于objective-c - 使用文本字段设置变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28162516/