gpt4 book ai didi

objective-c - subview 的位置错误

转载 作者:行者123 更新时间:2023-12-03 18:00:09 24 4
gpt4 key购买 nike

我想一个接一个地排列几个自定义 NSView。但是当我运行应用程序时, View 是使用不同的(双倍)帧原点值绘制的,而不是代码中设置的值。

这是带有 2 个 View 的简化代码:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application

float height1 = 40.0;
float height2 = 65.0;

float width = [[window contentView] frame].size.width;

NSRect r1 = NSMakeRect(0, 0, width, height1);
NSRect r2 = NSMakeRect(0, height1, width, height2);

MyView *c1 = [[MyView alloc] initWithFrame:r1];
MyView *c2 = [[MyView alloc] initWithFrame:r2];

[[window contentView] addSubview:c1];
[[window contentView] addSubview:c2];
}

MyView 的代码基本上仅由drawRect 组成:

- (void)drawRect:(NSRect)dirtyRect {
// Drawing code here.

NSRect cellFrame = [self frame];

// frame Y coordinates at superview
float superY = [self convertPoint:[self frame].origin
toView:[self superview]].y;

NSLog(@"superY:%f selfY:%f", superY, cellFrame.origin.y);


// top, bottom border and diagonal line of [self frame]
NSBezierPath* borderLine = [NSBezierPath bezierPath];

NSPoint pt1 = NSMakePoint(cellFrame.origin.x,
cellFrame.origin.y);
NSPoint pt2 = NSMakePoint(cellFrame.origin.x + cellFrame.size.width,
cellFrame.origin.y);
NSPoint pt3 = NSMakePoint(cellFrame.origin.x,
cellFrame.origin.y + cellFrame.size.height);
NSPoint pt4 = NSMakePoint(cellFrame.origin.x + cellFrame.size.width,
cellFrame.origin.y + cellFrame.size.height);

[borderLine moveToPoint:pt1];
[borderLine lineToPoint:pt2];
[borderLine lineToPoint:pt3];
[borderLine lineToPoint:pt4];

[[NSColor redColor] setStroke];
[borderLine setLineWidth:01];
[borderLine stroke];
}

这是结果(如您所见 - 第二个 View 的“y”坐​​标加倍,并且由于某种原因,该 View 仅部分绘制):

result with console

最佳答案

您混淆了 View 框架和边界矩形的概念。 “边界”是指 View 在其自己的坐标系中的尺寸,即原点为零,大小将是 View 的宽度和高度。

“框架”指的是 View 在其父 View 坐标系中的尺寸,即原点将是 View 在其父 View 中的位置,并且宽度和高度将与边界矩形的相同。

因此,对于示例代码中的日志记录,您不必要且错误地调用了“convertPoint”,因为您只需通过调用“[selfframe].origin”即可获取 View 的实际原点

绘图时,需要调用“[selfbounds]”来获取要绘制的矩形。在您的代码中,您正在调用“[self frame]”,它会在 super View 的坐标系(框架)中为您提供一个矩形,但这不起作用,因为绘图例程在 View 自己的(边界)坐标系中绘制(即以原点在 {0, 0})

一个异常(exception)是,如果 View 填充了其父 View 的全部内容,在这种情况下,您可以调用 [selfbounds] 或 [selfframe],因为两者都会返回相同的矩形。

我通过更改让你的代码正常工作

NSRect cellFrame = [自身框架];

NSRect cellFrame = [自身边界];

此外,记录 NSRect 最简单的方法是

NSLog(@"%@", NSStringFromRect([self frame])); 例如。

希望有帮助。

关于objective-c - subview 的位置错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7863029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com