将自定义 UIView 添加到 UIViewController - (void)loadView (Objective-C)
我正在参加编程课程(针对菜鸟),我需要以编程方式创建 UIViewController
graphViewController
的视图(无需界面生成器)。
该视图很简单,它仅由一个 IBOUtlet
组成,它是名为 GraphView
的 UIView
子类的实例。 graphView
响应多个多点触控手势,用于缩放和平移等,但我在 - (void)viewDidLoad
中处理所有这些内容。
我只是在下面的代码中创建 self.view
属性和 graphView
:
- (void)loadView
{
UIView *gvcView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view = gvcView;
[gvcView release];
GraphView *aGraph = [[GraphView alloc] initWithFrame:self.view.bounds];
self.graphView = aGraph;
[aGraph release];
}
当我运行应用程序时,我没有看到 graphView
> 在那里查看。我只是得到一个透明视图,其中显示“我的通用应用程序”标签。我很困惑。请帮忙。
如果您需要额外的代码,请告诉我。
谢谢!
更新:非常感谢 BJ Homer 的快速修复!
必须执行以下操作:
在末尾添加这行代码: [self.view addSubview:self.graphView];
。
我还遇到了这个奇怪的错误,其中 graphView
显示为全黑。这行代码修复了: self.graphView.backgroundColor = [UIColor WhiteColor];
就是这样!
最后一个问题:自定义 UIView 的默认背景色是黑色吗?
再次感谢!
I am taking a programming class (for noobs) and I need to create the UIViewController
graphViewController
's view programmatically (without interface builder).
The view is simple, it only consists of an IBOUtlet
which is an instance of a UIView
subclass called GraphView
. graphView
responds to several multitouch gestures for zooming and panning and what-not, but I handle all of that stuff in - (void)viewDidLoad
.
I am doing just the creation of the self.view
property and graphView
in the code below:
- (void)loadView
{
UIView *gvcView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view = gvcView;
[gvcView release];
GraphView *aGraph = [[GraphView alloc] initWithFrame:self.view.bounds];
self.graphView = aGraph;
[aGraph release];
}
When I run the app I do not see the graphView
view in there. I just get a transparent view which shows the "My Universal App" label. I'm stumped. Please help.
Let me know if you need additional code.
Thanks!
Update: Big thanks to BJ Homer for the quick fix!
had to do the following:
add this line of code: [self.view addSubview:self.graphView];
at the end.
I was also getting this strange bug where graphView
was showing up as completely black. This line of code fixed that: self.graphView.backgroundColor = [UIColor whiteColor];
And that's it!
Final question: Is the default background color black for a custom UIView?
Thanks again!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在将图形视图添加到父视图之前,UIKit 不知道在哪里显示它。
self.view
很特殊,因为这是-loadView
应该设置的属性。该视图将自动添加到屏幕上。但是你的图表视图只是漂浮在空中,直到你将它添加到某个地方。Until you add your graph view to a parent view, UIKit doesn't know where to display it.
self.view
is special, since that's the property that-loadView
is supposed to set. That view will automatically be added to the screen. But your graph view is just floating off in the ether until you add it somewhere.