删除随机生成的按钮

时间:2014-02-10 19:13:15

标签: ios iphone objective-c uiview uibutton

-(void)createTurtle是一个计时器动作

-(void)createTurtle {
     NSUInteger r = arc4random_uniform(284) + 1;

     int storedIntegerFromTurtle = [[NSUserDefaults standardUserDefaults] integerForKey:@"savedTurtleTag"];

     turtle = [[UIButton alloc] init];
     turtle.frame = CGRectMake(r, -50, 36, 47);
     [turtle setImage:[UIImage imageNamed:@"turtle.png"] forState:UIControlStateNormal];
     [turtle addTarget:self action:@selector(turtleTouched:) forControlEvents:UIControlEventTouchDown];
     [turtle setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
     [turtle setTag:storedIntegerFromTurtle+1];
     [self.view bringSubviewToFront:turtle];
     [self.view addSubview:turtle];


     [[NSUserDefaults standardUserDefaults] setInteger:turtle.tag forKey:@"savedTurtleTag"];
     NSLog(@"%i", turtle.tag);


     [UIView beginAnimations:nil context:nil];
     [UIView setAnimationDuration:15];
     [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

     turtle.frame = CGRectMake(turtle.frame.origin.x, self.view.frame.size.height, 36, 47);
     [UIView commitAnimations];
}

点击它,我将删除所选按钮:

 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
     CGPoint p =[((UITouch *)[touches anyObject]) locationInView:self.view];
     CGRect r= [turtle.layer.presentationLayer frame];

     int selectedTurtleTag;

     if (CGRectContainsPoint(r, p))
     {
         selectedTurtleTag = turtle.tag;
     }

     BOOL contains= CGRectContainsPoint(r, p);
     if(contains)
     {
         if (turtle.tag == selectedTurtleTag )
         {
             NSLog(@"Turtle-Tag: %i", selectedTurtleTag);
             [[self.view viewWithTag:selectedTurtleTag] removeFromSuperview];
         }
     }
}

我的问题是我只能删除最新创建的按钮。 我会删除任何点击的按钮。

1 个答案:

答案 0 :(得分:0)

看起来你有一个名为乌龟的财产。当你创建一个随机乌龟时,实例变量只引用那只乌龟,因为那时你刚刚分配/启动它。所以,最后创建的乌龟将永远被称为乌龟,这就是为什么这只适用于最后一个(你使用turtle.tag,在那一点上乌龟只是最后一个。)我会建议一个NSMutableArray的海龟和添加新创建的乌龟到createTurtle中的数组;然后在touchesBegan中穿过你的海龟阵列,找到被挖掘的海龟。