子视图删除并添加目标c/iphone

rus*_*ell 1 objective-c

我有一个UIViewController类,我在其中创建一个UIView实例.然后我用25个子视图初始化(表示填充)它,每个子视图包含一个图像(1,2,...,25).然后在这些图像中点击5次后,我调用了一个我使用过的函数

for(UIView *subview in [contentView subviews]) {
    [subview removeFromSuperview];//ContentView name of my view
}
Run Code Online (Sandbox Code Playgroud)

删除以前添加的子视图.然后我使用相同的approch添加25个新的子视图(图像1,2,3,.... 25).但这次没有添加子视图.有人可以给我一些添加和删除子视图的完整代码.

我第一次添加子视图时使用了以下代码

//create main window

contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
contentView.backgroundColor = [UIColor blackColor];
self.view = contentView;
[contentView release];

//adding 25 subview 1st time
int a=0;
int b=0;
for (int i = 0; i < 26; i++)
{

    CGRect dragRect = CGRectMake(0.0f, 0.0f, x, y);
    dragRect.origin = CGPointMake(a,b);
    DragView *dragger = [[DragView alloc] initWithFrame:dragRect];
    NSString *Flower = [[NSArray arrayWithObjects:@"1.png", @"2.png", @"3.png",@"4.png", @"5.png", @"6.png",@"7.png",@"8.png", @"9.png",@"10.png", @"11.png", @"12.png",@"13.png",@"14.png",@"15.png",@"16.png",@"17.png",@"18.png",@"19.png",@"20.png",@"21.png",@"22.png",@"23.png",@"24.png",@"25.png",@"26.png", nil] objectAtIndex:i];
    [dragger setImage:[UIImage imageNamed:Flower]];
    [dragger setUserInteractionEnabled:YES];
    [self.view addSubview:dragger];
    [dragger release];
    a+=10;
    b+=10;
}

//then removing 25 subview

//adding 25 subview 2nd times
Run Code Online (Sandbox Code Playgroud)

我使用相同的approch作为第一次添加第二次,但问题是当我删除25个子视图然后添加25个子视图时,这些子视图未添加/显示,视图保持相同.我厌倦了这些问题.有人帮助我.

Nik*_*uhe 10

问题可能在于删除旧视图的方式.您正在迭代它时修改数组,这不起作用.尝试使用此代码删除旧视图:

UIView* subview;
while ((subview = [[contentView subviews] lastObject]) != nil)
    [subview removeFromSuperview];
Run Code Online (Sandbox Code Playgroud)