從默認的「基於視圖」應用程序開始,我創建一個新視圖(ViewToDisplay,繼承自UIView的類),並在此視圖內創建一個圖層(LayerToDisplay)。視圖在框架周圍繪製一些東西,層也是如此,但這次是用虛線。這是爲了顯示/證明該圖層覆蓋整個視圖。使用來自應用程序委託的圖層創建UIView
下面是從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時)做了什麼,我沒有在代碼中做什麼?
謝謝!
P.S.這是理解它如何在幕後工作的練習,而不是使用最佳實踐。
就是這樣,它是有道理的。謝謝。 – pbz 2010-10-23 22:56:02