【问题标题】:How to dynamically create and delete view when user clicks on button [duplicate]用户单击按钮时如何动态创建和删除视图[重复]
【发布时间】:2017-01-04 12:36:41
【问题描述】:

请看一下这个场景。

  1. UIViewController 中有一个UIScrollView,在其中有一个UIView 和一个UIButton。当用户点击UIButton 时,应该添加一个新的UIView,具有相同的xinvialViewWidth + 30width身高UIButton

  2. 如果用户单击第二个UIButton,则必须创建一个新的第三个UIView 和第三个UIButton。同样,您必须创建 n 个视图。

  3. 在视图中会有另一个UIButton delete。当点击它时,UIView 应该从UIScrollView 中删除。

例如,如果要删除第 5 个UIView,则应单击第 5 个UIView 中的删除UIButton

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

【问题讨论】:

  • 你应该更喜欢UITableView
  • @matt 我只能使用滚动视图
  • @danh 我认为这是新问题,我没有找到任何重复的问题。

标签: ios objective-c uiview uiscrollview


【解决方案1】:

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

-(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];
    }

【讨论】:

  • 感谢您的快速回复,我会检查并通知您
  • @Hi rahul,在检测视图时出现了一些问题,问题是如果您在第 5 个视图中按删除按钮,则第 5 个视图必须删除而不是第 4 个视图。
  • 还有一个是如果点击添加按钮第一个视图第二个必须创建并且第一个视图中的添加按钮必须隐藏
  • 如果删除了中间视图,那么如何重新排列视图。
猜你喜欢
  • 2014-02-22
  • 1970-01-01
  • 2011-11-11
  • 1970-01-01
  • 2020-03-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多