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

标签 objective-c cocoa xcode4 nstextfield

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

- (IBAction)setXPos:(id)sender;

在我的 AppDelegate.h 文件中,我还创建了一个名为 XPosint。在我的 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/

相关文章:

objective-c - NSSegmentedControl - 有没有办法将(id)representedObject附加到控件的每个NSSegmentedCell部分?

cocoa - 从 NSOutlineView 中拖放

objective-c - 我的模式对话框崩溃了(Cocoa)

objective-c - NSMutableArray 添加/删除对象 + NSUserDefaults

ios - 动画 UILabel 增长和收缩

ios - 错误 0x1c8250 : double free memory in iphone

ios - 如何在 XCode 4.6.3 上添加 Apple ID 帐户?

ios - 在cocos2d-x中使用数据库(如sqlite)

ios - 如果行数超过 8 行,部分自定义 UITableViewCell 会很有趣

iphone - 负整数比较