SubClass UIButton但我无法得到" addTarget:action:forControlEvents:"执行?

时间:2012-03-06 04:09:43

标签: objective-c ios cocoa-touch

我已经将UIButton子类化为绘制图形,但“addTarget”将不起作用。

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents

我没有采取任何措施来调整该方法。

按钮图形在“触摸”上工作正常。

如果我使用标准的UIButton,那么“addTarget”工作正常。

不确定我错过了什么?

THX

#import <UIKit/UIKit.h>

@interface CButton : UIButton
{
    CGContextRef c;
    int myState;
}
@end

#import "CButton.h"

@implementation CButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    //NSLog(@"init state: %d", self.state);
    return self;
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
  //  myState = 1;
    myState = !myState;
   // NSLog(@"BeginState: %d", self.state);

    [self setNeedsDisplay];
}


- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
  //  myState = 0;
  //  NSLog(@"EndState: %d", self.state);
  //  [self setNeedsDisplay];

}

- (void)drawRect:(CGRect)rect
{
    // Drawing code

}
@end

1 个答案:

答案 0 :(得分:3)

当你完成处理事件时,你必须从你的事件处理程序调用super。按钮如何知道调用您的动作的触摸?

e.g。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
  //  myState = 1;
    myState = !myState;
   // NSLog(@"BeginState: %d", self.state);

    [self setNeedsDisplay];

    [super touchesBegan:touches withEvent:event]; // you need this
}

话虽如此,你原来帖子的评论是对的,UIButton的子类化可能会变得棘手。但看起来好像你控制的东西(主要是)。祝你好运!