在 IOS 中以编程方式创建视图(它是如何工作的)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4820094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatically creating Views in IOS (how does it work)?
提问by subject_x
A little background: I'm going through the CS193P iTune videos and I was stuck on the assignment 3 for the longest time. Basically, the assignment asks you to programmatically create a custom view to display a shape on the screen. I'm not using any view controllers by the way.
一点背景知识:我正在浏览 CS193P iTune 视频,并且我在作业 3 上停留的时间最长。基本上,该作业要求您以编程方式创建自定义视图以在屏幕上显示形状。顺便说一下,我没有使用任何视图控制器。
I could not get my view to display until I finally dragged a View object in Interface Builder and change the object name to my custom view class. So my question is when people say to programmatically create a view, are they just saying manually create the class but when you need to display it use IB? I can't help feeling like I misunderstood something?
在我最终在 Interface Builder 中拖动一个 View 对象并将对象名称更改为我的自定义视图类之前,我无法显示我的视图。所以我的问题是,当人们说以编程方式创建视图时,他们是否只是说手动创建类,但是当您需要显示它时使用 IB?我不禁觉得自己误会了什么?
edit: let me be more clear. My custom view has been initialized with a frame of 0, 0, 200, 150 and drawRect is overriden to draw a square in it. My view doesn't even show up if try adding it to the main window within my controller:
编辑:让我更清楚。我的自定义视图已使用 0、0、200、150 的帧进行初始化,并且 drawRect 被覆盖以在其中绘制一个正方形。如果尝试将其添加到我的控制器内的主窗口,我的视图甚至不会显示:
UIWindow* window = [UIApplication sharedApplication].keyWindow;
[window addSubview:polygonView];
However, if use drag a view in IB and change the class to my view class, it shows up fine.
但是,如果在 IB 中使用拖动视图并将类更改为我的视图类,则显示正常。
Edit: Added some code. This is my controller's awakeFromNib method where the view should be drawn.
编辑:添加了一些代码。这是我的控制器的awakeFromNib 方法,应在其中绘制视图。
- (void)awakeFromNib {
shape = [[PolygonShape alloc] initWithNumberOfSides:numberOfSidesLable.text.integerValue minimumNumberOfSides:3 maximumNumberOfSides:12];
polygonView = [[PolygonView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
UIWindow *window = [UIApplication sharedApplication].keyWindow;
polygonView.backgroundColor = [UIColor blackColor];
[window addSubview:polygonView];
[self updateInterface];
}
Part of my controller's updateInterface method:
我的控制器的 updateInterface 方法的一部分:
- (void)updateInterface {
[polygonView setPolygon:shape];
[polygonView setNeedsDisplay];
...
}
PolygonView.h
多边形视图.h
#import <UIKit/UIKit.h>
#import "PolygonShape.h"
@interface PolygonView : UIView {
IBOutlet PolygonShape *polygon;
}
@property (readwrite, assign) PolygonShape *polygon;
- (void)drawRect:(CGRect)rect;
@end
PolygonView.m
多边形视图.m
#import "PolygonView.h"
@implementation PolygonView
@synthesize polygon;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
nslog(@"initialized");
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGRect bounds = [self bounds];
[[UIColor grayColor] set];
UIRectFill(bounds);
CGRect square = CGRectMake(10, 10, 10, 100);
[[UIColor blackColor] set];
UIRectFill(square);
[[UIColor redColor] set];
UIRectFill(square);
NSLog(@"drawRect called");
}
@end
The polygonView is being initialized but the drawRect isn't being called.
正在初始化多边形视图,但未调用 drawRect。
回答by SushiGrass Jacob
To be even more specific to your question, the syntax would be
为了更具体地解决您的问题,语法将是
UIWindow* window = [UIApplication sharedApplication].keyWindow;
UIView *polygonView = [[UIView alloc] initWithFrame: CGRectMake ( 0, 0, 200, 150)];
//add code to customize, e.g. polygonView.backgroundColor = [UIColor blackColor];
[window addSubview:polygonView];
[polygonView release];
This is a pattern you will use for not only this but subviews afterwards. Also, another note is with many of the templates, the viewController is already set up with it's own view. When you want to make a custom view, you create it like above but instead of the method above you set the viewControllers view to the newly created view like so:
这是一种模式,您不仅将用于此,而且将用于之后的子视图。此外,另一个需要注意的是很多的模板中,的viewController已经设置了它自己的观点。当你想创建一个自定义视图时,你可以像上面那样创建它,但是你将 viewControllers 视图设置为新创建的视图,而不是上面的方法,如下所示:
viewController.view = polygonView;
Good luck!
祝你好运!
回答by RoyalFool
This is an old question, but I'm not sure he got the answer he expected - it sounds like he ran into the same problem I did where I created a UIViewController
subclass, whacked a UIViewController
in an interface builder nib but then couldn't figure out how to get the two working with one another.
这是一个老问题,但我不确定他是否得到了他期望的答案 - 听起来他遇到了与我在创建UIViewController
子类时遇到的相同问题,UIViewController
在界面构建器笔尖中重击了 a但后来无法弄清楚如何让两者相互合作。
If you made the nib seperately (so it wasn't made for you alongside your class) then you have to remember to click the UIViewController you placed in the interface builder, and then from the properties panel click the third tab button ('Custom Class'). The Class
will be the default base class UIViewController
etc - just open up this dropdown list and you'll see a list of all your custom subclasses, select it and volla - you've linked your custom element to the interface.
如果你单独制作了笔尖(所以它不是为你制作的),那么你必须记住点击你放置在界面构建器中的 UIViewController,然后从属性面板中点击第三个选项卡按钮('自定义类')。该Class
会是默认的基类UIViewController
等-只需打开此下拉列表,你会看到所有的自定义子类列表,选择它并volla -关联您的自定义元素的接口。
Hope that saves somebody the days it took me to figure out, I found some stupidly wonderful ways of getting around it until I realized the simple solution.
希望可以节省我花时间弄清楚的时间,我找到了一些愚蠢的奇妙方法来解决它,直到我意识到简单的解决方案。
回答by Saad Tasawar
hi just add this code,
嗨,只需添加此代码,
[window bringSubviewToFront:polygonView];
right after,
[window addSubview:polygonView];
回答by Ned
You need to have a view (or window) to add a subview to. The normal syntax is like this:
您需要有一个视图(或窗口)来添加子视图。正常的语法是这样的:
UIView *newView = [[UIView alloc] initWithFrame:mainView.bounds];
[mainView addSubview:newView];
[newView release];
Of course, if you have a custom object that inherits from UIView, you would use that instead of UIView. When you start a new project, create a "View based application", that will start you off with a view controller with an associated view (which can be accessed with "CustomViewController.view", which would replace "mainView" in the code snippet above).
当然,如果您有一个从 UIView 继承的自定义对象,您将使用它而不是 UIView。当您开始一个新项目时,创建一个“基于视图的应用程序”,它将以一个带有关联视图的视图控制器开始您(可以使用“CustomViewController.view”访问,它将替换代码片段中的“mainView”以上)。
If you want to create the view programmatically when the app starts, put the code in the "- (void)viewDidLoad" method of your view controller.
如果您想在应用程序启动时以编程方式创建视图,请将代码放在视图控制器的“- (void)viewDidLoad”方法中。
回答by hotpaw2
Somewhere in your active controller class, you can add a custom view to the current top level view.
在您的活动控制器类中的某处,您可以将自定义视图添加到当前顶级视图。
[ myCurrentTopView addSubview: myNewCustomView ];
It helps to allocate and initialize this custom view first.
它有助于首先分配和初始化此自定义视图。
Then, you can trigger some drawing in this custom view's drawRect by doing a:
然后,您可以通过执行以下操作在此自定义视图的 drawRect 中触发一些绘图:
[ myNewCustomView setNeedsDisplay ];
回答by fzwo
Did you set the background color of your view to something distinguishable?
您是否将视图的背景颜色设置为可区分的颜色?
Are you sure your view doesn't display, or is it just that you can't see it? Put an NSLog in the drawRect: method of your view (if you use a custom view class).
您确定您的视图没有显示,还是只是您看不到它?在视图的 drawRect: 方法中放置一个 NSLog(如果您使用自定义视图类)。
回答by nickolay
call
称呼
[super drawRect];
before your custom code in drawRect: body.
在 drawRect: body 中的自定义代码之前。
回答by Matjan
I had a very similar problem recently and here's what worked for me: It seems that when starting with an 'empty application' in Xcode 4.3.2 you have to set your view as the root view your main window using the setRootViewController method instead of addSubview. So:
我最近遇到了一个非常类似的问题,这对我有用:似乎在 Xcode 4.3.2 中以“空应用程序”开始时,您必须使用 setRootViewController 方法而不是 addSubview 将您的视图设置为主窗口的根视图. 所以:
// Initialize myView and then
[window setRootViewController:myView];
// instead of [window addSubview:myView];
// the rest as normal...
[window makeKeyAndVisible];
After that you can use the addSubview method to add additional views.
之后,您可以使用 addSubview 方法添加其他视图。