-1

是否可以将类分配给代码中的对象?我正在动态创建一个按钮,为该按钮加载一个图像,并且我有以下内容:

myButton = [[[NSButton alloc] initWithFrame:NSMakeRect(100,100,50,25)] autorelease];
[myButton setTitle:@"Done"];
[myButton setTarget:self];
[myButton setAction:@selector(mySelector:)];
[myButton setButtonType:NSMomentaryChangeButton];
[myButton setBordered:NO];
[myButton setImage:[NSImage imageNamed:@"myButton.png"]];
[myButton setImagePosition: NSImageOnly];
[[[self window] contentView] addSubview:myButton];

我还有一个要用于按钮的 NSButton 子类(例如 MyButtonClass.h/MyButtonClass.m),以便它具有特定的行为,但我不确定如何将该类分配给上述代码中的按钮.

这是可能的,还是只能/应该只在 Interface Builder 中完成?

4

2 回答 2

0

您可以使用MyButtonClass而不是启动按钮NSButton

myButton = [[[MyButtonClass alloc] initWithFrame:NSMakeRect(100,100,50,25)] autorelease];

于 2013-01-28T05:07:21.513 回答
0

创建按钮时,不要将它们创建为 NSButton,将它们创建为您的子类。例如,如果您有一个名为 MyButton 的 NSButton 子类,而不是类似:

NSButton *button = [[[NSButton alloc] initWithFrame:frame]autorelease];

你会有类似的东西:

MyButton *button = [[[MyButton alloc] initWithFrame:frame]autorelease];

这种方式按钮将是 MyButton 的一个实例。

于 2013-01-28T05:08:14.210 回答