开发者

Objective C: Removing previous ui elements

I'm producing a "brick" every second. When you tap it, it goes away. My problem is, when a second, or more, appear on the screen, tapping the previous one eliminates the most recent one, and can't be removed from the scr开发者_如何转开发een at all. The code I have is:

- (NSTimer *)getTimer{  
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:     @selector(produceBricks) userInfo:nil repeats:YES];
return timer;
}


-(IBAction) tapBrick {
//remove last brick
[bricks[count] removeFromSuperview];

//add to score
count++;
NSString *scoreString = [NSString stringWithFormat:@"%d", count];
score.text = scoreString;
}

-(void) produceBricks {
//determine x y coordinates
int xPos, yPos;
xPos = arc4random() % 250;
yPos = arc4random() % 370;

//create brick
bricks[count] = [[UIButton alloc] initWithFrame:CGRectMake(xPos,yPos + 60,70,30)];  
[bricks[count] setBackgroundColor:[UIColor blackColor]];
[bricks[count] addTarget:self action:@selector(tapBrick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:bricks[count]];


}

I know it has to do with the bricks[count] removeFromSuperview line being count is always increasing. How would I reference to the brick in the array that's being clicked instead of the current one?


If you add a sender argument, it'll automatically get set to the control which sent the action, so you can do something like the following:

-(IBAction) tapBrick:(id)sender {
    [sender removeFromSuperview];
}


Make the method tapBrick:(UIButton *)brick and you'll get a reference to the brick that was tapped as the argument.

Also, I strongly advise against using a C array for this. It's just asking for memory management trouble. Better to use an NSMutableArray and make sure to follow the memory management rules. With the code you've posted, your brick objects will never be released, and instead they'll just keep eating memory until your app exhausts its supply.


Views have a tag property for a reason — So you can identify views of the same type in the same view controller. Consider setting a unique tag for each of these bricks, and then removing the particular one you want to.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜