2011-12-21 107 views
5

使用以下代码创建视图。以编程方式创建uiview?

- (void)loadView { 

paintView=[[UIView alloc]initWithFrame:CGRectMake(0, 50, 320, 430)]; 
[paintView setBackgroundColor:[UIColor yellowColor]]; 
self.view = paintView; 
[paintView release]; 

但我的问题是整个屏幕填充黄色,但我想用指定的帧。 我在基于视图的应用程序中创建这个视图..我做错了什么,重写原始视图?

+0

但我从50在y轴的开始。 – NoviceDeveloper 2011-12-21 10:36:07

+0

为什么你将paintView分配给self.view self.view = paintView; – Aadil 2011-12-21 10:41:36

回答

20

你可以用下面的方法做到这一点。

- (void)loadView { 
    /// make a empty view to self.view 
    /// after calling [super loadView], self.view won't be nil anymore. 
    [super loadView]; 

    paintView=[[UIView alloc]initWithFrame:CGRectMake(0, 50, 320, 430)]; 
    [paintView setBackgroundColor:[UIColor yellowColor]]; 
    [self.view addSubview:paintView]; 
    [paintView release]; 
    }; 
+0

你的这个方法的自定义实现不应该调用超级如果你想执行任何额外的视图初始化,请在viewDidLoad方法中执行 – 2014-03-01 19:11:29

+0

@Alexey,也许在你的情况下,你不需要实现自定义的'loadView',并且这个答案有些古怪,在iOS SDK 4/5中,这个答案是正确的,[super loadView]会为'self.view'生成一个空视图, 。现在在iOS 7下,我不知道它是否有效 – AechoLiu 2014-03-04 06:29:59

+1

代码中有一个错字,所以不会让我编辑答案,方法是“addSubview”而不是“addSu” bView”。 – 2014-05-11 20:37:17

0

取代self.view =paintView; 通过

[self.view addSubview: paintView]; 
+0

没有成功....应用程序崩溃:( – NoviceDeveloper 2011-12-21 10:49:33

+2

你错过了[超级loadView]在你的loadview,添加这个,那么你的应用程序将不会崩溃 – iCoder4777 2011-12-21 10:56:27

+0

yup .. done..thnks – NoviceDeveloper 2011-12-21 10:58:48

0

我要变线3号中的loadView方法,你应该添加在主视图中的子视图上,而不是直接assiging它。

[self.view addSubview:paintview]; 
0
UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,35)]; 
newView.backgroundColor=[UIColor clearColor]; 
UITextView *mytext = [[UITextView alloc] initWithFrame:CGRectMake(5.0, 0.0, 100.0, 28.0)]; 
mytext.backgroundColor = [UIColor clearColor]; 
mytext.textColor = [UIColor blackColor]; 
mytext.editable = NO; 
mytext.font = [UIFont systemFontOfSize:15]; 
mytext.text = @"Mytext"; 
mytext.scrollEnabled=NO; 
[mytext release]; 
[newView addSubview:mytext]; 
[self.view addSubview:newView];