Ios 在屏幕旋转时更新UITabBar宽度
我正在以编程方式创建一个UITabBar。这是密码Ios 在屏幕旋转时更新UITabBar宽度,ios,objective-c,width,uitabbar,screen-rotation,Ios,Objective C,Width,Uitabbar,Screen Rotation,我正在以编程方式创建一个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"]
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
}
}
我有两个问题。如您所见,我已将cgy
值硬编码为411。在3.5英寸屏幕的纵向模式下,这看起来不错。但是你可以想象的问题是,如果我在一个4英寸的设备上运行它,选项卡栏就会出现在屏幕底部的上方。如果我旋转设备(不管屏幕大小),在横向模式下,选项卡栏会向下推,这样它就不会出现在屏幕上
bounds.size.width
使用两个变量表示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。Hi!非常感谢您的回复。当方向改变时,它在定位选项卡栏方面非常有效。然而,我遇到了一个小问题。比如,我将设备旋转到横向模式。选项卡栏的位置很好。然后,当我将其旋转回纵向视图时,先前在横向模式下创建的选项卡栏仍然显示为。我怎样才能摆脱它?再次感谢。:)我必须使用
UITabBar
而不是UITabBarController
,因为我正在实现一个自定义的UITabBar
。因为每次执行旋转时,都会向self.view添加一个新的子视图,所以在添加新的tbbar之前,需要清除先前添加的tbbar。代码可能类似于:for(UIView*self.view.subview中的视图){[view removeFromSuperview];}