此实例为使用代码动态的删除和添加标签(Label)
主要列举视图控制器文件,详见代码
1 #import "FCViewController.h" 2 3 @interface FCViewController () 4 @property (strong, nonatomic) NSMutableArray *Labels; 5 @end 6 7 @implementation FCViewController 8 int nextY = 40; 9 - (void)viewDidLoad 10 { 11 [super viewDidLoad]; 12 // Do any additional setup after loading the view, typically from a nib. 13 //设置背景色 14 self.view.backgroundColor = [UIColor greenColor]; 15 //实例化数组 16 self.Labels = [NSMutableArray array]; 17 //创建添加按钮并设置好参数与事件响应方法 18 UIButton *addBn = [UIButton buttonWithType: UIButtonTypeRoundedRect]; 19 addBn.frame = CGRectMake(30, 500, 60, 40); 20 [addBn setTitle: @"add" forState: UIControlStateNormal]; 21 [addBn addTarget: self action: @selector(add:) forControlEvents:UIControlEventTouchUpInside]; 22 //创建删除按钮并设置好参数与事件响应方法 23 UIButton *removeBn = [UIButton buttonWithType: UIButtonTypeRoundedRect]; 24 removeBn.frame = CGRectMake(230, 500, 60, 40); 25 [removeBn setTitle: @"remove" forState: UIControlStateNormal]; 26 [removeBn addTarget: self action: @selector(remove:) forControlEvents:UIControlEventTouchUpInside]; 27 //将按钮添加到view控件 28 [self.view addSubview: addBn]; 29 [self.view addSubview: removeBn]; 30 } 31 32 - (void)didReceiveMemoryWarning 33 { 34 [super didReceiveMemoryWarning]; 35 // Dispose of any resources that can be recreated. 36 } 37 //添加label 38 -(void) add: (id) sender 39 { 40 UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(80, nextY, 200, 30)]; 41 label.text = @"You are the champion!"; 42 [self.Labels addObject: label]; 43 [self.view addSubview: label]; 44 nextY += 40; 45 } 46 //删除lable 47 -(void) remove: (id) sender 48 { 49 if ([self.Labels count] > 0) { 50 //从view中删除最后一个Label 51 [[self.Labels lastObject] removeFromSuperview]; 52 [self.Labels removeLastObject]; 53 nextY -= 40; 54 } 55 } 56 @end
时间: 2024-12-11 20:19:37