在ViewController中添加子视图的数量

时间:2016-11-18 10:22:46

标签: ios objective-c view addsubview

enter image description here

在此图像中,当我按下添加视图按钮时,每次在同一个视图控制器中添加新的子视图并且还删除按钮按下的子视图也被删除。 任何人都知道你能帮助我的朋友。

2 个答案:

答案 0 :(得分:0)

What you have to do is to hold the subviews in an array.

Give the buttons (delete and add) the tag of the position in the array.

Then, when you click on "add view" or "delete" you will know where you have to insert or delete a subview in the array.

After that, set the button tags to the new indexes and then update your scrollview.

It would be easier in a tableview, because you don't have to calculate the content size and the positions in the scroll views

答案 1 :(得分:0)

我建议你根本不要使用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;
    }];


}

最后一件事是放置按钮

相关问题