上文中是在没有storyboard下创建UI,但是那样的方法既繁琐,又不符合MVC设计模式。
所以本文通过IB初始化界面,然后通过代码动态添加UILabel和删除UILabel
#import "ViewController.h"
@interface ViewController ()
@property (strong, nonatomic) NSMutableArray *labels;
@end
@implementation ViewController {
NSInteger _nextY;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.view setBackgroundColor:[UIColor grayColor]];
//初始化labels数组
self.labels = [NSMutableArray array];
//获取主视图的宽度
CGRect rect = [self.view bounds];
CGFloat width = rect.size.width;
//添加按钮设置在视图宽度1/3处
UIButton *addButton = [[UIButton alloc] initWithFrame:
CGRectMake(width/3 - 20, 50, 40, 20)];
[addButton setTitle:@"添加" forState:UIControlStateNormal];
[addButton addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:addButton];
//删除按钮设置在视图宽度2/3处
UIButton *removeButton = [[UIButton alloc] initWithFrame:
CGRectMake(2 * width/3 - 20, 50, 40, 20)];
[removeButton setTitle:@"删除" forState:UIControlStateNormal];
[removeButton addTarget:self action:@selector(remove:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:removeButton];
_nextY = 100;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)add:(id)sender {
CGRect rect = [self.view bounds];
CGFloat width = rect.size.width;
//创建一个UILable控件
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(width/2 - 80, _nextY, 160, 30)];
label.text = [NSString stringWithFormat:@"nextY = %ld", (long)_nextY];
[self.labels addObject:label];
[self.view addSubview:label];
_nextY += 50; //控制nextY的值加50
}
- (IBAction)remove:(id)sender {
NSLog(@"remove");
NSLog(@"%lu",(unsigned long)[self.labels count]);
if ([self.labels count] > 0) {
//将最后一个labels删除
[[self.labels lastObject] removeFromSuperview];
[self.labels removeLastObject];
_nextY -= 50;
}
}
@end