【发布时间】:2010-10-23 21:09:04
【问题描述】:
从默认的“基于视图”的应用程序开始,我创建了一个新视图(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);
}
和图层(LayerToDisplay.m)
- (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];
// doesn't seem to matter
//[vd setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
vd.frame = [UIScreen mainScreen].applicationFrame;
// call manually so that the layer gets created
[vd awakeFromNib];
[window addSubview:vd];
//[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
所以,我试图弄清楚用这两种方式创建/实例化视图有什么区别。自动过程(将 XIB 的类更改为 ViewToDisplay 时)做了哪些我没有在代码中做的事情?
谢谢!
附:这是一个了解其幕后工作原理的练习,而不是使用最佳实践。
【问题讨论】:
标签: iphone objective-c cocoa-touch uikit core-graphics