无法删除随机添加的 UIView

Unable to remove the randomly added UIViews

我随机添加了一个自定义 uiview,并尝试在单击该 uiview 的特定位置(UIVIew 的右上角)时删除 uiview,但我能够删除最后生成的 uiview,但不能删除所有 uiview是随机添加的。

这是我所做的:

- (IBAction)addView:(id)sender {

    NSString *min = @"60"; //Get the current text from your minimum and maximum textfields.
    NSString *max = @"110";

    int randNum = rand() % ([max intValue] - [min intValue]) + [min intValue];
    butLab = [[buttonLabel alloc] initWithFrame:CGRectMake(randNum, randNum, 82, 36)];

    [self.view addSubview:butLab];


}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    CGPoint locationPoint = [[touches anyObject] locationInView:butLab];
    NSLog(@"%f %f",locationPoint.x,locationPoint.y);
    if (CGRectContainsPoint(butLab.bounds, [touches.anyObject  locationInView:butLab])==YES){
        if ( (locationPoint.x>=64 && locationPoint.x<=80)
         &&  (locationPoint.y>=3  && locationPoint.y<=12) ) {

            NSLog(@"pressed close button");
           [butLab removeFromSuperview]; //here when i clicked on top right,only the last view that is added is getting removed
        }
    }
}

谁能告诉我一个一个删除 UIViews 的最佳方法?

创建一个右上角有 UIButton 的自定义 UIView,并在触及内部

时将其全部删除

每次调用 addView: 方法时,您都会将 butLab 重新定义为新的 buttonLabel,因此只有最后一个被删除。当你创建一个 buttonLabel 时,你应该将它添加到一个数组中,并让数组的所有成员自己调用 removeFromSuperview,

[buttonLabelsArray makeObjectsPerformSelector:@selector(removeFromSuperview)];

另一种不使用数组的方法是遍历 self.view 的子视图,并在属于 class buttonLabel 的任何对象上调用 removeFromSuperview。

编辑后:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

for (buttonLabel *but in buttonLabelArray) {
     CGPoint locationPoint = [[touches anyObject] locationInView:but];
    if (CGRectContainsPoint(but.bounds, [touches.anyObject  locationInView:but])==YES){
        if ( (locationPoint.x>=64 && locationPoint.x<=80)
            &&  (locationPoint.y>=3  && locationPoint.y<=12) ) {

            NSLog(@"pressed close button");
            [but removeFromSuperview]; //here when i clicked on top right,only the last view that is added is getting removed
        }
    }
}

}