gpt4 book ai didi

ios - 更新屏幕旋转时的 UITabBar 宽度

转载 作者:行者123 更新时间:2023-11-29 04:06:16 29 4
gpt4 key购买 nike

我正在以编程方式创建 UITabBar。这是代码,

UITabBarItem *item1 = [[UITabBarItem alloc] initWithTitle:@"Item 1" image:[UIImage imageNamed:@"dashboard"] tag:1];
UITabBarItem *item2 = [[UITabBarItem alloc] initWithTitle:@"Item 2" image:[UIImage imageNamed:@"documents"] tag:2];
UITabBarItem *item3 = [[UITabBarItem alloc] initWithTitle:@"Item 3" image:[UIImage imageNamed:@"mail"] tag:3];
UITabBarItem *item4 = [[UITabBarItem alloc] initWithTitle:@"Item 4" image:[UIImage imageNamed:@"packages"] tag:4];

NSArray *tabbaritems = [[NSArray alloc] initWithObjects:item1, item2, item3, item4, nil];

CGRect bounds = [[UIScreen mainScreen] bounds];
UITabBar *tbbar = [[UITabBar alloc] initWithFrame:CGRectMake(0, 411, bounds.size.width, 49)];
[tbbar setItems:tabbaritems];
[self.view addSubview:tbbar];

- (BOOL)shouldAutorotate
{
return YES;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
//update UITabBar width
}
else {
//update UITabBar width
}
}

我有 2 个问题。正如您所看到的,我已将 CGFloat y 值硬编码为 411。这在纵向模式下的 3.5 英寸屏幕上看起来不错。但你可以想象的问题是,如果我在 4 英寸设备上运行它,标签栏会出现在屏幕底部上方。如果我旋转设备(无论屏幕大小如何),在横向模式下,选项卡栏会向下推,因此它根本不会出现在屏幕上。

  1. 如何动态设置 UITabBar 的位置无论它以哪种旋转方式运行,它总是固定在屏幕上屏幕底部?

另一个问题是宽度。当第一次创建 UITabBar 实例时,我使用这行 bounds.size.width 设置它。

  1. 如何在屏幕旋转时更新它,以便它扩展以填充屏幕的整个宽度?

最佳答案

使用两个变量来代表 y 偏移和宽度。使用标志来交换纵向和横向的 y 偏移和宽度。旋转后重新加载 View 。

并在 viewDidLoad 中从其 super View 中删除旧的 tbbar。

...
CGRect bounds = [[UIScreen mainScreen] bounds];
CGFloat tabbarAnchor = bounds.size.height;
CGFloat tabbarWidth = bounds.size.width;
if (_flag == 1) {
tabbarWidth = bounds.size.height;
tabbarAnchor = bounds.size.width;
}
UITabBar *tbbar = [[UITabBar alloc] initWithFrame:CGRectMake(0, tabbarAnchor-69, tabbarWidth, 49)];
[tbbar setItems:tabbaritems];
[self.view addSubview:tbbar];
...

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
//update UITabBar width
_flag = 1;
[self viewDidLoad];
}
else {
//update UITabBar width
_flag = 0;
[self viewDidLoad];
}
}

仍然建议您使用已经实现旋转的UITabBarController。

关于ios - 更新屏幕旋转时的 UITabBar 宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15151422/

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