首页 > 代码库 > 我的IOS学习之路(一):使用代码创建UI界面

我的IOS学习之路(一):使用代码创建UI界面

  此实例为使用代码动态的删除和添加标签(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)viewDidLoad10 {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)didReceiveMemoryWarning33 {34     [super didReceiveMemoryWarning];35     // Dispose of any resources that can be recreated.36 }37 //添加label38 -(void) add: (id) sender39 {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 //删除lable47 -(void) remove: (id) sender48 {49     if ([self.Labels count] > 0) {50         //从view中删除最后一个Label51         [[self.Labels lastObject] removeFromSuperview];52         [self.Labels removeLastObject];53         nextY -= 40;54     }55    }56 @end

 

我的IOS学习之路(一):使用代码创建UI界面