应用所选图片时,UITabBarButton索引已更改

时间:2019-06-24 12:48:32

标签: objective-c uitabbarcontroller uitabbar uitabbaritem

当前,我在通过UITabBarButton应用所选图像时遇到了问题。当我这样做时,它会更改tabBar.items中的UITabBarbutton的层次结构。真的不知道为什么会这样。发布代码-

 UIWindow *keyWindow = [[UIApplication sharedApplication]keyWindow];
 UITabBarController *tabBarController =(UITabBarController*)[keyWindow rootViewController];
 UITabBar *tabBar = tabBarController.tabBar;
 UITabBarItem *targetTabBarItem = [[tabBar items] objectAtIndex:1]; // whichever tab-item
 [targetTabBarItem setSelectedImage:image];
 [targetTabBarItem setImage:image];

我在这里做什么-

从服务器获取图像,并将其应用于特定的UItabBarbutton图像。每当我设置它时,它都会使用UITabbarButton并将其插入所有UITabBarButtons的最后一个位置。

Initial Images

Initial Image

每当从服务器更改映像时,其层次结构都会像这样更改- After Effect Image

enter image description here

在这里我们可以看到,按钮的顺序最初是Tab1,Tab2和Tab3,而在更改所选图像后,按钮的顺序变成了Tab1,Tab3和Tab2。这表明选定的图像索引弹出并始终插入到TabBarButtons集合的最后。如果我最初在索引0处更改所选图像,则顺序为Tab2,Tab3和Tab1。

因此,这里的任何人都可以给出一个简短的想法,指出代码中出了什么问题? 抱歉,很长的帖子,也要提前感谢。

谢谢。

1 个答案:

答案 0 :(得分:0)

在视图调试器中显示的标签栏视图层次结构的顺序应完全独立于支持标签栏项目数组的tabBarController的tabBar属性。

我的猜测是您看到视图层次结构顺序的这种调整的原因,因为更改image属性将导致重新绘制它或将其删除/重新添加到视图层次结构中,因此它将是最后添加到其中的项目(这完全不会影响tabBarController.tabBar.items的顺序)

如果仅更改选项卡栏项目的标题,就会看到相同的情况。

我操纵了一个按钮来更改索引1标签栏项目图像,类似于您显示的代码,然后在标签中显示标签栏顺序:

- (IBAction)changeTabBarImage:(id)sender {
    UIWindow *keyWindow = [[UIApplication sharedApplication]keyWindow];
    UITabBarController *tabBarController =(UITabBarController*)[keyWindow rootViewController];
    UITabBar *tabBar = tabBarController.tabBar;
    UITabBarItem *targetTabBarItem = [[tabBar items] objectAtIndex:1]; // whichever tab-item
    NSMutableString *tabBarOrder = [[NSMutableString alloc] init];
    for (NSUInteger tabBarIndex = 0; tabBarIndex < [tabBar items].count; tabBarIndex++) {
        [tabBarOrder appendString:[NSString stringWithFormat:@"index: %lu title: %@\n", tabBarIndex, [[tabBar items] objectAtIndex:tabBarIndex].title]];
    }
    self.firstLabel.text = [NSString stringWithString:tabBarOrder];
    UIImage *image = [UIImage imageNamed:@"sync"];
    [targetTabBarItem setSelectedImage:image];
    [targetTabBarItem setImage:image];
}

唯一更改过的图像是索引1处的标签栏,并且即使视图调试器中的视图层次结构顺序发生了变化(如您的屏幕快照所示),tabBarController.tabBar.items的顺序也保持不变。 / p>

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CocoaViewsGuide/WorkingWithAViewHierarchy/WorkingWithAViewHierarchy.html

如果您看到的内容有所不同,我建议您添加一些其他代码,因为我无法仅凭自己的付出来重现该问题。

相关问题