2012-03-06 3 views
1

UIButton을 서브 클래 싱하여 그래픽을 그리지 만 "addTarget"이 작동하지 않습니다.SubClassing UIButton하지만 "addTarget : action : forControlEvents :"실행할 수 없습니다?

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

나는이 방법을 조정할 때 아무 것도하지 않았습니다.

"터치"에서 버튼 그래픽이 정상적으로 작동합니다.

표준 UIButton을 사용하면 "addTarget"이 정상적으로 작동합니다.

내가 무엇을 놓치고 있는지 잘 모르겠습니까 ??

들으

#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 
+0

이 질문에 대한 답변은 없지만 'UIButton'을 하위 클래스로 만들면 대개 재앙이 발생합니다. 대신에'UIControl'을 서브 클래 싱하려고합니다. 좀 더 많은 일이지만 장기적으로 행복해집니다. –

+0

동의, 나는 항상 UIButton 서브 클래 싱은 나쁜 생각이라고 들었다. – stephenmuss

+0

'@ interface'의 서브 클래스와'initWithFrame :'과'initWithCoder :'메소드의 구현을 보여주십시오. – Costique

답변

3

당신은 당신이 모든 이벤트를 처리 할 때 이벤트 핸들러에서 슈퍼를 호출해야합니다. 버튼이 당신의 행동을 부르는 터치를 어떻게 알 수 있습니까?

- (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을 서브 클래 싱하는 것이 까다로울 수 있습니다. 그러나 그것은 당신이 통제하에있는 것처럼 보이는 (대부분) 것입니다. 행운을 빕니다!

+0

두 건드리기 모두를 위해 슈퍼해야했다 .Began and touchesEnded ... thx – Woof

관련 문제