0

I am writing the program to generate the button periodically after every second. when I click the button I want that clicked button to hide.I have tried in my following code but the button is getting hidden for the last created button.

NSTimer *timer=[[NSTimer alloc]init];
timer=[NSTimer scheduledTimerWithTimeInterval:1.0f
                                           target:self
                                         selector:@selector(subtractTime)
                                         userInfo:nil
                                          repeats:YES];


-(void)subtractTime{
    x=arc4random()%260;
    y=arc4random()%500;
    color=@[@"redColor",@"greenColor",@"yellowColor",@"orangeColor",@"blueColor",@"blackColor",@"grayColor"];
    z=arc4random()%7;

    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.button addTarget:self action:@selector(show) forControlEvents:UIControlEventTouchUpInside];

    self.button.frame = CGRectMake(x, y, 60.0, 60.0);
   [self.button setTitle:@"Button" forState:UIControlStateNormal];

    self.button.backgroundColor=[UIColor redColor];
    [self.view addSubview:self.button];

}
-(void)show{
   self.button.hidden=YES;
}
4

2 回答 2

4
//....  
  [self.button addTarget:self action:@selector(show:) forControlEvents:UIControlEventTouchUpInside];  
//...
- (void) show:(id)sender{

    [sender setHidden:YES];
}
于 2013-10-17T12:13:35.567 回答
0

每次调用计时器方法时,您都应该创建单独的按钮.....

尝试这个.....

-(void)subtractTime{
    x=arc4random()%260;
    y=arc4random()%500;
    color=@[@"redColor",@"greenColor",@"yellowColor",@"orangeColor",@"blueColor",@"blackColor",@"grayColor"]; 
    z=arc4random()%7;

    UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
    [btn addTarget:self action:@selector(hideButton:) forControlEvents:UIControlEventTouchUpInside];

    btn.frame = CGRectMake(x, y, 60.0, 60.0);
   [btn setTitle:@"Button" forState:UIControlStateNormal];

    btn.backgroundColor=[UIColor redColor];
    [self.view addSubview:btn];

}
-(IBAction)hideButton:(id)sender
{
   sender.hidden=YES;

}
于 2013-10-17T12:21:40.670 回答