【问题标题】:Adding Number of Subviews in ViewController在 ViewController 中添加子视图数
【发布时间】:2016-11-18 10:22:46
【问题描述】:

在这张图片中,当我按下“添加视图”按钮时,每次在同一个视图控制器中添加新的子视图,并且删除按钮按下的子视图也被删除。 哪位知道的朋友可以帮帮我。

【问题讨论】:

  • 您能在这里向我们展示您为实现这一目标所做的工作吗?
  • 我之前尝试过添加一两个视图,但我的要求是用户每次需要一个新的子视图时都按下添加视图按钮。
  • 您可以发布添加视图代码以便我们在这里为您提供帮助吗?
  • 我以编程方式采取的这个观点,代码太大了。
  • 您想要添加子视图的超级视图是滚动视图还是表格视图?

标签: ios objective-c view addsubview


【解决方案1】:

你要做的就是将子视图保存在一个数组中。

给按钮(删除和添加)数组中位置的标签。

然后,当您单击“添加视图”或“删除”时,您将知道必须在数组中插入或删除子视图的位置。

之后,将按钮标签设置为新索引,然后更新您的滚动视图。

在表格视图中会更容易,因为您不必计算内容大小和滚动视图中的位置

【讨论】:

    【解决方案2】:

    我建议你根本不要使用 UIViews 标签,这不是可维护性。 因此,首先让我们从 viewcontrollers 类开始,并在其中添加三个属性:

    @property(nonatomic, strong) UIButton *deleteButton;
    @property(nonatomic, strong) UIButton *addButton;
    @property(nonatomic, strong) NSMutableArray *addedSubviews;
    

    viewDidLoad 方法:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        self.deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
        [self.view addSubview:self.deleteButton];
        [self.deleteButton addTarget:self action:@selector(onDeleteSubview) forControlEvents:(UIControlEventTouchUpInside)];
    
        self.addButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
        [self.view addSubview:self.addButton];
        [self.addButton addTarget:self action:@selector(onAddSubview) forControlEvents:(UIControlEventTouchUpInside)];
    
        self.addedSubviews = [NSMutableArray new];
    }
    
    - (void)onDeleteSubview {
         UIView *viewToDelete = [self.addedSubviews lastObject];
        [viewToDelete removeFromSuperview];
        [self.addedSubviews removeLastObject];
        [self.view layoutSubviews];
    }
    
    - (void)onAddSubview {
        UIView *desiredView = [UIView new]; // create view you need
        [self.view addSubview:desiredView];
        [self.addedSubviews addObject:desiredView];
        [self.view layoutSubviews];
    }
    

    这里我们遍历每个视图并对其进行布局

    - (void)viewWillLayoutSubviews {
    
        [super viewWillLayoutSubviews];
    
        float start_y_point = 0; //as you wish
        float padding = 10;
    
        [self.addedSubview enumerateObjectsUsingBlock:^(UIView *view, NSUInteger idx, BOOL * _Nonnull stop) {
            view.frame = CGRectMake({<#CGFloat x#>}, start_y_point + padding, {<#CGFloat width#>}, {<#CGFloat height#>})
            start_y_point += view.frame.size.height + padding;
        }];
    
    
    }
    

    最后一件事是放置按钮

    【讨论】:

    • 但是为什么呢?您是否根据需要更换了所有位置?
    猜你喜欢
    • 2014-01-20
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多