我建议你根本不要使用 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;
}];
}
最后一件事是放置按钮