2

I'm currently trying to use a UIButton titled "X" as a way to remove a Sprite from the view.

Basically, my code works so that when a Sprite is touched, a message is sent to the delegate (View Controller) that passes the (Sprite *)sprite which has been selected. In this method, I draw a UIButton on top of that sprite. So far, so good.

However, the issue is I now want my UIButton to run a @selector to remove that sprite whenever the button is touched down.

Initially I tried this:

-(void)spriteSelected:(Sprite *)sprite{ //delegate method implementation
      [sprite.button addTarget:self action:@selector(removeSprite:sprite) forControlEvents: UIControlEventTouchDown]
}    

-(void)removeSprite:(Sprite *)sprite{
        [sprite removeFromSuperView];}

However, it seems I can't put arguments into the selector like that. Any ideas on how I can adjust this?

Thanks

user339946
  • 5,961
  • 9
  • 52
  • 97
  • 1
    Hi, check this link http://stackoverflow.com/questions/3716633/passing-parameters-on-button-actionselector – SriPriya Jan 10 '12 at 06:01

2 Answers2

3

You should do this in the Sprite class, so in the original class:

-(void)spriteSelected:(Sprite *)sprite{
      [sprite youAreSelected];
} 

In the Sprite class:

-(void)youAreSelected {
    [self.button addTarget:self action:@selector(removeMe:) forControlEvents: UIControlEventTouchDown];
}

-(void)removeMe:(id)sender {
    [self removeFromSuperView];
}
personak
  • 539
  • 4
  • 15
2

A selector is simply a method identifier, not an invocation of the method, so you can't include parameters as though it were a method call.

The usual way to manage something like this would be for the view controller to look at the button that was touched, figure out which sprite it's associated with, and remove the sprite. It was probably the view controller that put both the sprite and the button in the view in the first place, so it should have all the information it needs.

Caleb
  • 124,013
  • 19
  • 183
  • 272