Home  >  Q&A  >  body text

objective-c - cocoa-不知道drawRect:为什么调用?

在学习别人的代码,准备写一个状态栏应用。
AppDelegate里出现了这段代码

- (void)setStatusImageAndToolTip:(enum InfoStatus)status {
    NSString *name = [nameArray objectAtIndex:status];
    NSString *toolTip = [toolTipArray objectAtIndex:status];
    NSImage *image = [NSImage imageNamed:name];
    CGFloat length = image.size.width / image.size.height * statusBarHeight * 0.8;
    [image setSize:NSMakeSize(length, statusBarHeight * 0.8)];
    statusView.image = image;
    statusView.alternateImage = image;
    [statusView.alternateImage setTemplate:YES];
    statusItem.length = length;  //此处调用drawRect
    statusView.toolTip = toolTip;
}

这段代码是在observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context函数里调用的。在当状态变量status改变后,调用setStatusImageAndToolTip函数。
由于我自己的项目里并没有用到状态改变,就没有写这部分代码。但是导致了在运行时不执行drawRect:函数,所以在状态栏没有显示图标。
回头研究代码时,发现drawRect是在statusItem.length赋值时调用的。不知道为什么?

PHP中文网PHP中文网2728 days ago362

reply all(1)I'll reply

  • 阿神

    阿神2017-05-02 09:24:19

    In the official documentation:

    If you simply change the geometry of the view, the view is typically
    not redawn.

    The calling timing of drawRect is determined by the system (when it is displayed for the first time, etc.), which means that drawRect will not be called by the system in some cases.
    Use the following method to force drawRect to be called to update the view in the next redraw cycle

    • setNeedsDisplay

    reply
    0
  • Cancelreply