2013-03-01 113 views
0

我以编程方式创建UITabBar。这里是代码,更新屏幕旋转的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. 如何在屏幕旋转上更新它,使其扩展为填充屏幕的整个宽度 ?

回答

1

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

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

+0

嗨!非常感谢回复。当方向改变时,它在定位TabBar方面效果很好。不过,我遇到了一个小问题。比方说,我将设备旋转到横向模式。 TabBar的位置很好。然后,当我将其旋转回纵向视图时,之前在横向模式下创建的TabBar仍然显示为[this](http://i.imgur.com/NHdwY4u.png)。我怎样才能摆脱它?再次感谢。 :) – Isuru 2013-03-04 04:00:18

+0

我有种不得不使用'UITabBar'而不是'UITabBarController',因为我正在实现一个自定义的'UITabBar'。 – Isuru 2013-03-04 04:01:37

+0

由于每次执行旋转时,新的子视图都会添加到self.view,您需要在添加新的tbbar之前清除以前添加的tbbar。代码可能是这样的:'for(UIView * view in self.view.subviews){ [view removeFromSuperview]; }' – 2013-03-04 13:57:21