ViewController.m
#import "ViewController.h"
@interface ViewController ()
//存放label的數(shù)組
@property(nonatomic,strong)NSMutableArray *labelArr;
@end
@implementation ViewController
//控制y坐標(biāo)的變量
int newY = 80;
- (void)viewDidLoad {
??? [super viewDidLoad];
??? self.view.backgroundColor = [UIColor lightGrayColor];
??? //初始化添加按鈕
??? UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
??? //設(shè)置背景顏色
??? 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];
??? //設(shè)置背景顏色
??? 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];
??? //給數(shù)組開辟空間
??? self.labelArr = [NSMutableArray array];
}
-(void)addLabel{
???
??? //判斷如果lable小于10個(gè) 添加label
??? if (self.labelArr.count < 10) {
??????? UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, newY, 200, 40)];
??????? label.text = @"ok";
??????? label.textAlignment = NSTextAlignmentCenter;
?????? //arc4random獲取隨機(jī)數(shù)
??????? //顏色
??????? 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];
??????? //從數(shù)組中刪除數(shù)據(jù)
??????? [self.labelArr removeLastObject];
??????? newY -=60;
??? }else{
??????? [[[UIAlertView alloc]initWithTitle:@"提示" message:@"沒有hello了!" delegate:self cancelButtonTitle:@"確定" otherButtonTitles: nil] show];
???
??? }
}
@end