我正在以编程方式创建一个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英寸设备中运行它,标签栏会出现在屏幕底部的上方。如果我旋转设备(尽管有屏幕尺寸),在横向模式下,标签栏会向下按,因此它根本不会出现在屏幕上。
另一个问题是宽度。我在第一次创建UITabBar实例时使用此行bounds.size.width
设置它。
答案 0 :(得分: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。