【发布时间】:2023-03-04 05:02:01
【问题描述】:
我正在编写一个 iPhone 应用程序(与大多数应用程序一样)支持自动旋转:您旋转手机,它的视图会相应地旋转和调整大小。
但我为navigationItem.titleView(导航栏的标题区域)分配了一个自定义视图,当手机旋转时我无法正确调整该视图的大小。
我知道你在想什么,“只需将其 autoresizingMask 设置为 UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight”,但这并不是那么简单。当然,如果我不设置视图的autoresizingMask,那么我的视图不会调整大小;我希望它调整大小。
问题是,如果我确实设置了它的autoresizingMask,那么只要该视图可见,它就会正确调整大小;但是titleView 的大小在这种情况下会变得混乱:
- 运行应用程序,手机保持纵向模式。一切看起来都不错。
- 执行一些操作,使应用程序将另一个视图推送到导航堆栈。例如。单击导致调用
[self.navigationController pushViewController:someOtherViewController animated:YES]的表格行或按钮。 - 查看子控制器时,将手机旋转到横向。
- 单击“返回”按钮返回顶层视图。此时,标题视图混乱了:尽管您以横向模式握住手机,但标题视图的大小仍然与您以纵向模式握持一样。
- 最后,将手机旋转回纵向模式。现在事情变得更糟了:标题视图的尺寸缩小了(因为导航栏变小了),但由于它已经太小了,现在它太多太小了。
如果您想自己重现此内容,请按照以下步骤操作(这有点工作):
- 使用 Xcode 的“基于导航的应用程序”向导制作应用程序。
- 进行设置,以便顶级表视图具有行,当您单击它们时,会将详细视图推送到导航堆栈上。
-
在顶级视图控制器和详细视图控制器中都包含此代码:
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } -
仅在顶级视图控制器中包含此代码:
- (void)viewDidLoad { [super viewDidLoad]; // Create "Back" button UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Master" style:UIBarButtonItemStylePlain target:nil action:nil]; self.navigationItem.backBarButtonItem = backButton; [backButton release]; // Create title view UILabel* titleView = [[[UILabel alloc] initWithFrame:CGRectMake(0,0,500,38)] autorelease]; titleView.textAlignment = UITextAlignmentCenter; titleView.text = @"Watch this title view"; // If I leave the following line turned on, then resizing of the title view // messes up if I: // // 1. Start at the master view (which uses this title view) in portrait // 2. Navigate to the detail view // 3. Rotate the phone to landscape // 4. Navigate back to the master view // 5. Rotate the phone back to portrait // // On the other hand, if I remove the following line, then I get a different // problem: The title view doesn't resize as I want it to when I: // // 1. Start at the master view (which uses this title view) in portrait // 2. Rotate the phone to landscape titleView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; self.navigationItem.titleView = titleView; } 最后,按照我的重现步骤。
那么……我做错了吗?有没有办法让我的 titleView 始终正确调整大小?
【问题讨论】:
标签: iphone ios uinavigationbar