1

我有一个包含子视图的自定义 NSView——为了解决这个问题,顶层视图只是充当容器并自动调整大小以适应窗口。它的子视图从窗口边缘绘制一个 10 像素插入的矩形,底部除外,它应该被窗口剪裁,直到它被调整大小以显示整个矩形。但是,它并没有按照我的意图运行,而是在其父视图的高度小于它的高度时缩小矩形的高度。我如何避免这种情况并让它保持在适当的高度,而不是在超级视图较小时被剪裁?

父视图的实现代码为:

- (id)initWithFrame:(NSRect)frameRect {
    self = [super initWithFrame:frameRect];
    if (self) {
        subView = [[SubView alloc] initWithFrame:frameRect];
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
    [[NSColor grayColor] set];
    [subView setFrame:NSMakeRect(10, 10, dirtyRect.size.width - 20, 500)];
    [self addSubview:subView];
}

- (BOOL)isFlipped {
    return YES;
}

子视图只是:

- (void)drawRect:(NSRect)dirtyRect {
    [[NSColor blackColor] set];
    [NSBezierPath strokeRect:dirtyRect];
}

- (BOOL)isFlipped {
    return YES;
}
4

2 回答 2

2

您的子视图很可能具有自动调整大小的蒙版。你可以通过调用 -setAutoresizingMask: 和 NSViewNotSizable 来清除它。

如果超级视图不应该调整它的任何子视图的大小,您可以考虑使用 -setAutoresizesSubviews:

于 2010-03-22T18:18:04.453 回答
2

正如ericgorr指出的那样,autoResizingMask应该处理调整大小的问题。

但是,我注意到您正在添加您的子视图drawRect,这不是正确的地方。drawRect在程序的生命周期中被多次调用,但addSubview:只需要(而且应该)调用一次,如下所示:

- (id)initWithFrame:(NSRect)frameRect {
    self = [super initWithFrame:frameRect];
    if (self) {
        subView = [[SubView alloc] initWithFrame:frameRect];
        [self addSubview:subView]; // this view now owns subView ...
        [subView release];         // ... so we can release our copy
    }
    return self; 
} 

- (void)drawRect:(NSRect)dirtyRect { 
    [[NSColor grayColor] set]; 
    [subView setFrame:NSMakeRect(10, 10, [self bounds].size.width - 20, 500)];
} 

Note also the use of [self bounds] instead of dirtyRect. dirtyRect is a rectangle describing the region which needs to be redrawn. This will not always be the entire bounding rectangle of your view. [self bounds], on the other hand, will always represent the entire bounds of your view, regardless of which portion is being redrawn.

于 2010-03-22T19:43:33.347 回答