【发布时间】:2012-01-22 09:55:21
【问题描述】:
我有一个自定义类,该类有一个UIButton 实例变量。我在类指定初始化器中添加了这段代码:
theFishDeathView = [UIButton buttonWithType:UIButtonTypeCustom];
[theFishDeathView setFrame:CGRectMake(15, 15, 50, 50)];
[theFishDeathView setImage:[UIImage imageNamed:@"Small fish - death.png"] forState:UIControlStateNormal];
所以这应该正确分配/初始化按钮。确实,当它被调用时,按钮 get 会显示在屏幕上(当然也可以作为子视图添加)。
现在,我在我的对象上调用这个方法:
[theFishDeathView addTarget:self action:@selector(sellFish) forControlEvents:UIControlEventTouchDown];
这里是sellFish 方法:
-(void) sellFish {
thePlayer.dollars += worthInDollars * 3;
[theFishDeathView removeFromSuperview];
}
但是当我尝试按下按钮时,它不会调用该方法。我在这里遗漏了什么吗?
为了完整起见,这里是 Fish.h 文件。很明显theFishDeathView是Fish对象的一个实例成员。
#import <Foundation/Foundation.h>
@interface Fish : NSObject
{
float cookingTime;
float weight;
int worthInDollars;
NSString *name;
NSArray *animaionImages;
int fishMovementSpeed;
}
// Will be used to display
@property (nonatomic, retain) UIImageView *theFishImageView;
@property (nonatomic, retain) UIButton *theFishDeathView;
// Create setter / getter methods
@property (nonatomic, retain) NSString *name;
@property (readonly) int worthInDollars;
@property (readonly) int fishMovementSpeed;
-(id) initWith: (NSString *)theName andWeight: (float)theWeight andCookingTime: (float)theCookingTime andValue: (int)theValue andMovementSpeed: (int)speed;
-(CGRect) newFrameWithWidth:(int)width andHeight:(int)height;
-(void) killFish;
// Cooking methods
-(void) startCooking;
-(void) isDoneCooking;
-(void) isOverCooked;
-(void) sellFish;
@end
【问题讨论】:
-
请包含您尝试调用的 sellFish 方法。是卖鱼还是卖鱼:?
-
我添加了 sellFish 方法,它不需要任何参数,所以应该可以像 sellFish 一样
-
请注意 - theFishDeathView,是一个由 Fish * 对象指向的 UIButton,所以我必须更改 addTarget: self 吗?我尝试将其更改为 nil 但这并没有解决它,所以我想知道那里是否还有其他尝试?
-
[theFishDeathView addTarget:self action:@selector(sellFish) forControlEvents:UIControlEventTouchDown];通过调试检查此行是否执行?
-
它正在被执行。我想知道它是否与将 self 指定为目标有关?因为我的意思是,theFishDeathView(UIBUtton *)是 Fish 类的实例成员。并且该方法是在该 Fish 类中定义的,但我只是假设我应该说 self 并且它会在 UIButton * 所在的类中查找方法?
标签: objective-c uibutton selector target-action