从默认的“基于视图”应用程序开始,我创建了一个新视图(ViewToDisplay,继承自UIView的类),在这个视图中,我创建了一个层(LayerToDisplay)。视图围绕框架的周长绘制一些东西,图层也绘制一些东西,但这次是用虚线绘制的。这是为了显示/证明图层覆盖了整个视图。
这是ViewToDisplay.m中的相关代码
- (void) awakeFromNib
{
ld = [[LayerToDisplay alloc] init];
ld.frame = self.frame;
[self.layer addSublayer:ld];
[ld setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextSetRGBStrokeColor(context, 255/255.0, 0/255.0, 0/255.0, 1);
CGContextSetLineWidth(context, 1);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, 320, 460);
CGContextAddLineToPoint(context, 0, 460);
CGContextAddLineToPoint(context, 320, 0);
CGContextClosePath(context);
CGContextStrokePath(context);
}
- (void)drawInContext:(CGContextRef)context
{
CGContextBeginPath(context);
CGContextSetRGBStrokeColor(context, 0/255.0, 255/255.0, 0/255.0, 1);
CGContextSetLineWidth(context, 1);
CGFloat dashes[]={3,6};
CGContextSetLineDash(context, 0, dashes, 3);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, 320, 460);
CGContextAddLineToPoint(context, 0, 460);
CGContextAddLineToPoint(context, 320, 0);
CGContextClosePath(context);
CGContextStrokePath(context);
}
如果我将默认的ApplicationNameViewController.xib视图更改为我的类(ViewToDisplay),它将按预期工作。如果我试着从应用程序委托中实例化它,视图会正确显示,但层会向下移动,即层绘制的内容不会与视图绘制的内容重叠。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
ViewToDisplay *vd = [[ViewToDisplay alloc] init];
vd.frame = [UIScreen mainScreen].applicationFrame;
[vd awakeFromNib];
[window addSubview:vd];
[window makeKeyAndVisible];
return YES;
}
所以,我试图找出用这两种方法创建/实例化视图之间的区别。自动进程(当将XIB的类更改为ViewToDisplay时)做了什么我没有在代码中做的事情?
P、 这是一个了解它如何在幕后工作的练习,而不是使用最佳实践。