代码之家  ›  专栏  ›  技术社区  ›  pbz

从应用程序委托创建带层的UIView

  •  1
  • pbz  · 技术社区  · 14 年前

    从默认的“基于视图”应用程序开始,我创建了一个新视图(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];
        // 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、 这是一个了解它如何在幕后工作的练习,而不是使用最佳实践。

    1 回复  |  直到 14 年前
        1
  •  3
  •   Michal    14 年前

    awakeFromNib 使用 ld.frame = self.bounds; 而不是 ld.frame = self.frame; .

    要解释发生了什么-如果视图由视图控制器加载,则该视图的帧将从点(0,0)开始。如果您使用的是UIScreen的applicationFrame,它将按状态栏的大小向下放置。