2011-04-18 107 views
0

我是Objective-C的新手,希望能够将一个整数属性附加到每个物理按钮,我可以在界面生成器中看到;我还需要许多其他变量,所以只需使用“标记”属性是不够的。我创建了一个子类,但似乎无法改变这个类的实例中的这些新变量。如何从我创建的子类的实例访问变量?

myButton.h--------- 

@interface myButton : UIBUtton 
{ 
    int hiddenNumber; 
} 

@property(nonatomic, assign) int hiddenNumber; 


myButton.m-------- 
#import "myButton.h" 

@implementation myButton 
@synthesize hiddenNumber; 


ViewController.h------- 
IBOutlet myButton *button1; // This has been connected in Interface Builder. 

ViewController.m------- 
[button1 setAlpha:0]; // This works (one of the built-in attributes). 
[button1 setHiddenNumber:1]; // This won't (one of mine)! It receives a 'Program received signal: "SIGABRT". 

任何帮助将是伟大的,谢谢。

回答

3

在Interface Builder中,您必须将Button的类型设置为您的自定义按钮。

在“身份检查器”下是自定义类。将它从UIButton设置为myButton。

+0

感谢马克看看,我会尝试这一点,如果我有任何问题,我我还可以尝试另一点建议。 – indoorGinger 2011-04-20 07:17:20

1

UIButton的子类化问题只是为了添加属性来存储数据,您最终只能将自己限制为自定义按钮类型。由于这些按钮是类集群的一部分,因此不再需要舍入。我的建议?使用Associative References。在这篇文章Subclass UIButton to add a property

的UIButton + Property.h

#import <Foundation/Foundation.h> 

@interface UIButton(Property) 

@property (nonatomic, retain) NSObject *property; 

@end 

的UIButton + Property.m

#import "UIButton+Property.h" 
#import <objc/runtime.h> 

@implementation UIButton(Property) 

static char UIB_PROPERTY_KEY; 

@dynamic property; 

-(void)setProperty:(NSObject *)property 
{ 
    objc_setAssociatedObject(self, &UIB_PROPERTY_KEY, property, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 
} 

-(NSObject*)property 
{ 
    return (NSObject*)objc_getAssociatedObject(self, &UIB_PROPERTY_KEY); 
} 

@end 
+0

嗨乔,谢谢你的回答,请原谅我对此的无知,但是有什么缺点是不能使用'圆角矩形'按钮? – indoorGinger 2011-04-20 07:16:20

+0

如果您从不想使用它们,则无。你基本上将你的自己锁定在一个自定义的'UIButton'中,并且不能将你的自定义属性用于未来的任何'+(id)buttonWithType:(UIButtonType)buttonType'方法,因为它们从类集群返回不同的按钮类型。此外,您不必在界面构建器中更改自定义类以使用属性。只需在源文件中包含类别标题即可。 – Joe 2011-04-20 12:53:42