Piero
Piero

Reputation: 9273

Subclass UIButton and detect UIControlEventTouchUpInside

i'm trying to detect when a button was pressed, so respond to the UIControlEventTouchUpInside event, i have tried this:

- (void)setHighlighted:(BOOL)highlighted
{
    if (highlighted)
    {
        self.titleLabel.textColor = [UIColor whiteColor];
        [self.circleLayer setFillColor:self.color.CGColor];
    }
    else
    {
        [self.circleLayer setFillColor:[UIColor clearColor].CGColor];
        self.titleLabel.textColor = self.color;
    }
}

but it's only when there is the finger on the button and not released, how i can detect in the subclass the touchup inside action?

Upvotes: 0

Views: 345

Answers (2)

streem
streem

Reputation: 9144

What you could do is add a target in your init method, and have a boolean to keep the button state :

in CustomButton.h

@property(nonatomic,assign) BOOL selected; 

in CustomButton.m

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.selected = NO;
        [self addTarget:self action:@selector(toggle:) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}


- (IBAction)toggle:(id)sender{
    self.selected = !self.selected;
    if (self.selected)
    {
        self.titleLabel.textColor = [UIColor whiteColor];
        [self.circleLayer setFillColor:self.color.CGColor];
    }
    else
    {
        [self.circleLayer setFillColor:[UIColor clearColor].CGColor];
        self.titleLabel.textColor = self.color;
    }
}

Upvotes: 2

iPatel
iPatel

Reputation: 47049

Use UIControlEventTouchDown instead of UIControlEventTouchUpInside so it's action method will call when your button will be down.

Upvotes: 0

Related Questions