生活随笔
收集整理的這篇文章主要介紹了
Iphone代码创建视图
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
要想以編程的方式創建視圖,需要使用視圖控制器中定義的viewDidLoad方法,只有在運行期間生成UI時才需要實現該方法。
在此只貼出viewDidLoad方法的代碼,因為只需要在這個方法里面編寫代碼:
[cpp] view plaincopyprint?
-?(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?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];????????}??
- (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:
[cpp] view plaincopyprint?
[myview?addSubview:mylabel];??????[myview?addSubview:mybutton];??????self.view?=?myview;??
[myview addSubview:mylabel];[myview addSubview:mybutton];self.view = myview;
總結
以上是生活随笔為你收集整理的Iphone代码创建视图的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。