iosiphoneuibuttonuicontroluicontrolevents

UIButton subclass not responding to super methods?


I would like to create a UIButton that toggles its image. Once clicked the image should change to another one and stay that way until clicked again.

I have added both images to the default and selected states of the button on interface builder.

Now, I have created a UIButton subclass. My idea is to intercept the tap to that button and change the button state. So I added this to the UIButton subclass, hoping one of these methods would be triggered by a tap.

- (void)sendAction:(SEL)action
                to:(id)target
          forEvent:(UIEvent *)event {

  [super sendAction:action to:target forEvent:event];

  // toggle state
  [self setSelected:![self isSelected]];

}


- (void)sendActionsForControlEvents:(UIControlEvents)controlEvents {
  [super sendActionsForControlEvents:controlEvents];

  // toggle state
  [self setSelected:![self isSelected]];

}


- (void)touchesEnded:(NSSet *)touches
           withEvent:(UIEvent *)event {

  [super touchesEnded:touches withEvent:event];
  // toggle state
  [self setSelected:![self isSelected]];
}

None of these methods are triggered. Any clues?


Solution

  • I could be barking up the wrong tree (pun partially intended), but I created a Swift project that does what I think you're asking for. I realize you're using ObjC, but for sake of time on my part I made it in Swift. In any case, it'll give you somewhere to start.

    Here is the repo on GitHub: Click Here
    --> Note: You'll need >= Xcode 6 to run the project.

    A few things to note in the project:
    1 - Be sure and connect the Button on Main.storyboard to the class you've created.
    2 - In Swift, the class MyButton: UIButton is the line that implements UIButton for the class. I'm certain there's an ObjC equivalent, this Stack Overflow question may be helpful syntactically: Click Here

    Hopefully some of this is helpful!

    Good luck,
    Kyle