且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

目标C:删除以前的ui元素

更新时间:2023-12-03 18:15:52

视图具有 tag 属性的原因-您可以在同一视图控制器中识别相同类型的视图。考虑为每个砖块设置一个唯一的标签,然后删除想要的特定砖块。


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 screen 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?

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.