gpt4 book ai didi

iphone - 为什么我的 subview 无法根据设备方向正确居中?

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

我正在尝试以编程方式创建一个自定义 View Controller ,其 subview 位于屏幕中心。我已经成功了,当我导航到此 View 时,居中 View 出现在中心,并且当您旋转设备时会正确旋转。

但是,在这个导航应用程序中,如果我在纵向模式下进入自定义 View ,那么应该居中的 View 确实会将自己定位在不是中心的位置屏幕。我已经将所有必要的自动调整大小属性放在 View 、 Controller 、 parent 、祖母、圣母上......并且我已经用完了可以粘贴自动调整大小蒙版的东西,但这个例子看起来仍然很糟糕。

我确信我错过了对某些神奇方法的调用,该方法可以解决所有问题,但我还没有弄清楚要调用什么或在哪里调用(setNeedsDisplay?setNeedsLayout?)。为了展示这个问题,我创建了一个完整的示例,位于 https://github.com/gradha/iPhone-centered-rotation-test您可以在模拟器或设备中克隆并运行它。我从 Apple 的导航 Controller 创建了这个,只需添加一个假单元来推送我手动创建的 View 。

自定义 View 可以在 https://github.com/gradha/iPhone-centered-rotation-test/blob/master/Classes/CenteredViewController.m 找到这是负责创建居中 subview 的 loadView 方法:

/* Try to force the parent view to be as we want it. */
self.view.backgroundColor = [UIColor yellowColor];
self.view.autoresizesSubviews = YES;
self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight |
UIViewAutoresizingFlexibleWidth;

/* Top left blue square, for reference. */
blue_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 130, 130)];
[self.view addSubview:blue_];
blue_.backgroundColor = [UIColor blueColor];
[blue_ release];

/* Create red centered rectangle. */
red_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
red_.backgroundColor = [UIColor redColor];
red_.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin |
UIViewAutoresizingFlexibleTopMargin |
UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin;
red_.center = self.view.center;
[self.view addSubview:red_];
[red_ release];

Here's a link to a screen capture walkthrough of the application ,首先进入纵向模式并旋转屏幕(工作正常),然后进入横向模式并旋转(取决于旋转侧,它看起来很糟糕)。当您以横向模式进入 View 时,根据方向,红色方 block 的左上角将是 196x34 或 140x34,这差别太大了。

在横向模式下进入 View 并遵循自动旋转时,为了使这些 subview 正确居中,我缺少什么?

最佳答案

似乎在其中一种横向方向上,在 loadView 中, Controller 的 View 原点设置为 (0, 20),这会混淆 View 添加到后发生的旋转和自动调整大小。屏幕。奇怪的是,在所有其他方向上它都是 (0, 0)。

要解决此问题,请在 [super loadView] 之后添加此行:

self.view.frame = self.view.bounds;

详细说明:由于帧原点不在 (0, 0),因此 self.view.center 的概念在其使用的上下文中是不正确的。 center 属性是该 View 的中心,在其 super View 中可见。您真正想要的是 View 边界的中心。

通过将 View 框架重置为 View 边界,您可以有效地将原点更改回 (0, 0),并且可以正确使用 center

关于iphone - 为什么我的 subview 无法根据设备方向正确居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5431045/

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