无法删除随机添加的UIViews

时间:2015-02-22 05:19:36

标签: ios objective-c uiview

我随机添加了一个自定义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的最佳方法吗?

2 个答案:

答案 0 :(得分:2)

每次调用addView:方法时,都会重新定义butLab为新的buttonLabel,这就是为什么只删除最后一个buttonBabel的原因。创建buttonLabel时,应将其添加到数组中,并让数组的所有成员自己调用removeFromSuperview,

[buttonLabelsArray makeObjectsPerformSelector:@selector(removeFromSuperview)];

没有数组的另一种方法是循环遍历self.view的子视图,并在类buttonLabel的任何对象上调用removeFromSuperview。

编辑后:

- (void)touchesBegan:(NSSet *)触及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
        }
    }
}

}

答案 1 :(得分:0)

创建一个在其右上角有UIView的自定义UIButton,并在内部触摸此按钮时将其全部删除