如何在用户单击按钮时动态创建和删除视图

时间:2017-01-04 12:36:41

标签: ios objective-c uiview uiscrollview

请完成此方案。

  1. UIViewController中有一个UIScrollView,其中有UIViewUIButton。当用户点击UIButton时,应添加新的UIView,其中 x invialViewWidth + 30 width < / em>,身高UIButton

  2. 如果用户点击了第二个UIButton,则必须创建一个新的第三个UIView,其中包含第三个UIButton。同样,您必须创建 n 数量的视图。

  3. 在视图中,会有另一个UIButton 删除。点击后,UIView应从UIScrollView中删除。

  4. 例如,如果您要删除第5个UIView,则应点击第5个UIButton中的删除UIView

    我经历了很多问题,但我没有得到正确答案。

1 个答案:

答案 0 :(得分:0)

创建一个自定义视图,其中包含两个按钮添加和删除。你可以这样做:

-(UIView *)getNewViewWithTag:(NSInteger )tag{
        UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];//Set appropriate frame
        UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
        addButton.frame = CGRectMake(0,0,50,50); //Set appropriate frame
        addButton.tag = tag;
        [addButton addTarget:self action:@selector(addNewView:) forControlEvents:UIControlEventTouchUpInside];
        [containerView addSubview:addButton];

        UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        deleteButton.frame = CGRectMake(50,0,50,50); //Set appropriate frame
        deleteButton.tag = tag;
        [deleteButton addTarget:self action:@selector(deleteView:) forControlEvents:UIControlEventTouchUpInside];
        [containerView addSubview:deleteButton];
        containerView.tag = tag;
        return containerView;
    }
    -(void)addNewView:(id)button{
        NSInteger tag = [button tag];
        UIView *view = [self getNewViewWithTag:tag+1];
        //set appropriate frame
        [scrollView addSubview: view];
    }
    -(void)deleteView:(id)button{
        NSInteger tag = [button tag];
        UIView *viewToDelete = [scrollView viewWithTag:tag];
        [viewToDelete removeFromSuperview];
    }