ViewController.m
#import "ViewController.h"
@interface ViewController ()
//存放label的数组
@property(nonatomic,strong)NSMutableArray *labelArr;
@end
@implementation ViewController
//控制y坐标的变量
int newY = 80;
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor lightGrayColor];
//初始化添加按钮
UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//设置背景颜色
addBtn.backgroundColor = [UIColor orangeColor];
addBtn.frame = CGRectMake(50, 20, 100, 30);
[addBtn setTitle:@"添加" forState:UIControlStateNormal];
[addBtn addTarget:self action:@selector(addLabel) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:addBtn];
UIButton *deleBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//设置背景颜色
deleBtn.backgroundColor = [UIColor orangeColor];
deleBtn.frame = CGRectMake(200, 20, 100, 30);
[deleBtn setTitle:@"删除" forState:UIControlStateNormal];
[deleBtn addTarget:self action:@selector(deleLabel) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:deleBtn];
//给数组开辟空间
self.labelArr = [NSMutableArray array];
}
-(void)addLabel{
//判断如果lable小于10个 添加label
if (self.labelArr.count < 10) {
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, newY, 200, 40)];
label.text = @"ok";
label.textAlignment = NSTextAlignmentCenter;
//arc4random获取随机数
//颜色
label.backgroundColor = [UIColor colorWithRed:arc4random()%10*0.1 green:arc4random()%10*0.1 blue:arc4random()%10*0.1 alpha:1];
[self.labelArr addObject:label];
[self.view addSubview:label];
newY += 60;
}else{
[[[UIAlertView alloc]initWithTitle:@"提示" message:@"hello太多了!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil] show];
}
}
-(void)deleLabel{
if (self.labelArr.count >0) {
//将label从视图中移除
[[self.labelArr lastObject] removeFromSuperview];
//从数组中删除数据
[self.labelArr removeLastObject];
newY -=60;
}else{
[[[UIAlertView alloc]initWithTitle:@"提示" message:@"没有hello了!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil] show];
}
}
@end