添加刪除標(biāo)簽

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容