0

我正在以编程方式创建一个 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 的位置,以便它在任何旋转中运行的任何屏幕,它总是固定在屏幕底部?

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

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

1 回答 1

1

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

并从 viewDidLoad 中的父视图中删除旧的 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 。

于 2013-03-02T02:29:09.777 回答