selectionIndicatorImage

selectionIndicatorImage

我将自定义UITabBarItem图像用于中间项,因此我必须为selectionIndicatorImage制作一个UIImage
根据这个答案Same question as mine,我编写了代码。


UIStoryboard *iPhoneSB = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
UITabBarController *tbc = [iPhoneSB instantiateInitialViewController];
self.window.rootViewController = tbc;
tbc.delegate = self;

tbc.selectedIndex = 2;

UITabBar *tb = tbc.tabBar;

NSArray *items = tb.items;
for (UITabBarItem *tbi in items) {
  UIImage *image = tbi.image;
  tbi.selectedImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  tbi.image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}
[tbc.tabBar setSelectionIndicatorImage:[UIImage imageNamed:@"selected-tabbar-bg.png"]];

和委托方法:
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {

    if (tabBarController.selectedIndex==2) {
        [tabBarController.tabBar setSelectionIndicatorImage:nil];
    } else {
        [tabBarController.tabBar setSelectionIndicatorImage:[UIImage imageNamed:@"selected-tabbar-bg.png"]];
    }
}

它的工作,多亏了答案。但是有一些问题。第一次触摸任何selectionIndicatorImage内部后,UITabBarItem仍然为零(请确保中间没有)。

例如:

在应用程序启动时,选择了第三个UITabBar。触摸第一项-selectionIndicatorImage效果很好(选择了第一项)。触摸第三项(特定项)-没有selectionIndicator(很好)。但是之后,如果我先触摸例如-也没有selectionIndicator。
如果此后我再触摸第二个,就会出现。
我哪里错了?提前致谢。

最佳答案

将日志放入委托方法中,并检查项目中是否将selectionIndicatorImage设置为nil。

 - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {

 if(tabBarController.tabBar.selectionIndicatorImage == nil)
     NSLog("Starting point delegate: Selection indicator image is nill");
 else
     NSLog("Starting Point Of delegate: Selection indicator image is available");

 if (tabBarController.selectedIndex==2) {
     [tabBarController.tabBar setSelectionIndicatorImage:nil];
 } else {
     [tabBarController.tabBar setSelectionIndicatorImage:[UIImage imageNamed:@"selected-tabbar-bg.png"]];
 }

 if(tabBarController.tabBar.selectionIndicatorImage == nil)
     NSLog("Ending point delegate: Selection indicator image is nill");
 else
     NSLog("Ending Point Of delegate: Selection indicator image is available");
   }

10-08 12:17