开发者

Objective C: Having buttons work inside a mutable array

I'm making a game that involves have buttons move across the screen until the user taps them. What I have so far is buttons moving across being generated randomly. My problem is when a new button is created, the last one stops moving. I'm trying to stick them into an array, but I'm not sure that's really gonna keep them moving.

-(void) generateStickFig:(NSTimer *)timer {

int x = random() % 100;
NSMutableArray *enemies = (NSMutableArray *)timer.userInfo;
if (x == 1) {
    s开发者_运维百科tickFig = [[UIButton alloc] initWithFrame:CGRectMake(0, 650, 50, 50)];
    [stickFig setBackgroundColor:[UIColor blackColor]];
    [stickFig addTarget:self action:@selector(tapFig:) forControlEvents:UIControlEventTouchUpInside];
//  [enemies setObject:object forKey:[NSString stringWithFormat:@"object%i",i]];
    [enemies addObject:stickFig];
    int b = [enemies count];
    [self.view addSubview:stickFig];
    arrayNum++;
}



CGPoint oldPosition = stickFig.center;
stickFig.center = CGPointMake(oldPosition.x + 1 , oldPosition.y);


}


Where the buttons are stored is immaterial to moving them. You need to have a routine which animates them. You can do this by hand by moving them a small amount in response to a timer tick. The easiest method there would be fast enumeration over your array.

So you'd have the generation routine you have in your statement, a movement routine, and a touch IBAction handler which removes the button from the array. The generation routine, and the movement routine would both be called in your timer tick handler. (I tend to call that method "handleTick")

In high level psuedo-code it'd be something like this:

//tick handler
handleTick:
  one out a hundred times, make a new button
          give it a random starting location
          store it in the buttons array
  every time:
    for button in buttons:
      move button a few pixels

//button touch handler
buttonWasTouched:button :
  [buttons removeObject: button];

I'm just getting into the system provided animation, so I don't know if your button can accept touches while being animated, but I wouldn't be surprised.


In order to know what button was touched from the array, you can use the tag option for the button:

- (IBAction) buttonTouched:(id) sender withEvent:(UIEvent *) event
{
UIButton *btn = (UIButton *)sender;
// in my case, I store the position on the array as a tag for the button
NSUInteger index = btn.tag;
UIControl *control = sender;
// Now you know what button was touched
// Apply actions on to it: remove from superview, animate explosion...
}

Cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜