以编程方式创建UIButton - 不会调用操作?

时间:2012-01-22 09:55:21

标签: objective-c uibutton selector target-action

我有一个自定义类,该类有一个UIButton实例变量。我在类指定的初始化程序中添加了此代码:

theFishDeathView = [UIButton buttonWithType:UIButtonTypeCustom];
[theFishDeathView setFrame:CGRectMake(15, 15, 50, 50)];
[theFishDeathView setImage:[UIImage imageNamed:@"Small fish - death.png"] forState:UIControlStateNormal];

所以这应该正确分配/初始化按钮。确实如此,调用此按钮时屏幕上会显示按钮(当然也会添加为子视图)。

现在,我在我的对象上调用此方法:

[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

3 个答案:

答案 0 :(得分:1)

 -(void) sellFish:(id)sender

和(使用售后食品后的:

[theFishDeathView addTarget:self
                 action:@selector(sellFish:)
       forControlEvents:UIControlEventTouchUpInside];

答案 1 :(得分:0)

  [theFishDeathView addTarget:self
                 action:@selector(sellFish)
       forControlEvents:UIControlEventTouchUpInside];

你写了UIControlEventTouchDown而不是UIControlEventTouchDown

答案 2 :(得分:0)

我希望人们知道我发现了错误(在Apple开发者论坛的帮助下) - 这是内存泄漏。我试图向僵尸对象发送消息(即解除分配的对象)。我认为通过将其添加为子视图来保留它,但我完全忘记了它是作为子视图添加的BUTTON,而不是包含按钮的类。所以班级本身已经解除分配,按钮被保留,他就是我仍然可以按下它的原因。

对于处理类似问题的其他人,请打开plist.info文件中的Zombie Objects Enabled。这样,您将收到如下错误消息:“尝试将操作发送到解除分配的对象”。

感谢您试图帮助我:)