要想以编程的方式创建视图,需要使用视图控制器中定义的viewDidLoad方法,只有在运行期间生成UI时才需要实现该方法。
在此只贴出viewDidLoad方法的代码,因为只需要在这个方法里面编写代码:
- - (void)viewDidLoad
- {
- self.navigationItem.title = @"动态创建UI";
- UIView *myview = [[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
- myview.backgroundColor = [UIColor blackColor];
- CGRect frame = CGRectMake(10, 15, 300, 20);
- UILabel *mylabel = [[UILabel alloc]initWithFrame:frame];
- mylabel.text = @"这是动态创建的label";
- mylabel.backgroundColor = [UIColor clearColor];
- mylabel.font = [UIFont fontWithName:@"Verdana" size:20];
- mylabel.textColor = [UIColor lightGrayColor];
- mylabel.textAlignment = UITextAlignmentCenter;
- frame = CGRectMake(10, 70, 300, 50);
- //UIButton *mybutton = [[UIButton alloc]initWithFrame:frame];
- UIButton *mybutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
- mybutton.frame = frame;
- [mybutton setTitle:@"点我" forState:UIControlStateNormal];
- mybutton.backgroundColor = [UIColor clearColor];
- [mybutton addTarget:self action:@selector(buttonclc) forControlEvents:UIControlEventTouchUpInside];
- [myview addSubview:mylabel];
- [myview addSubview:mybutton];
- self.view = myview;
- [mylabel release];
- [super viewDidLoad];
- // Do any additional setup after loading the view from its nib.
- }
- (void)viewDidLoad
{
self.navigationItem.title = @"动态创建UI";
UIView *myview = [[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
myview.backgroundColor = [UIColor blackColor];
CGRect frame = CGRectMake(10, 15, 300, 20);
UILabel *mylabel = [[UILabel alloc]initWithFrame:frame];
mylabel.text = @"这是动态创建的label";
mylabel.backgroundColor = [UIColor clearColor];
mylabel.font = [UIFont fontWithName:@"Verdana" size:20];
mylabel.textColor = [UIColor lightGrayColor];
mylabel.textAlignment = UITextAlignmentCenter;
frame = CGRectMake(10, 70, 300, 50);
//UIButton *mybutton = [[UIButton alloc]initWithFrame:frame];
UIButton *mybutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
mybutton.frame = frame;
[mybutton setTitle:@"点我" forState:UIControlStateNormal];
mybutton.backgroundColor = [UIColor clearColor];
[mybutton addTarget:self action:@selector(buttonclc) forControlEvents:UIControlEventTouchUpInside];
[myview addSubview:mylabel];
[myview addSubview:mybutton];
self.view = myview;
[mylabel release];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
解释下上面的代码:
上面代码有三段:
第一段创建的是UIView对象,它可以作为容器容纳其他视图。
第二段是创建一个Label视图。
第三段是创建一个UIButton视图。
注意,千万不要忘记将创建的视图加入第一步创建的view中,也不要忘记了将创建的view赋值给当前窗口的view:
- [myview addSubview:mylabel];
- [myview addSubview:mybutton];
- self.view = myview;
[myview addSubview:mylabel];
[myview addSubview:mybutton];
self.view = myview;