How do I change background color of UITabItem when item is selected

前端 未结 11 1070
暖寄归人
暖寄归人 2021-02-01 19:15

I would like a different background color when the user selects a tab bar item than when it is unselected.

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 19:33

    Follow this Steps:

    1. Create SubClass of UITabBarController

    2. Go to viewDidAppear of UITabBarController subclass

    3. Now Find the size of TabBarItem,

      UITabBar *tabBar = self.tabBar;
      CGSize imgSize = CGSizeMake(tabBar.frame.size.width/tabBar.items.count,tabBar.frame.size.height);
      
    4. Now Create the image with that size,

      //Create Image
      UIGraphicsBeginImageContextWithOptions(imgSize, NO, 0);
      UIBezierPath* p =
      [UIBezierPath bezierPathWithRect:CGRectMake(0,0,imgSize.width,imgSize.height)];
      [[UIColor blueColor] setFill];
      [p fill];
      UIImage* finalImg = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
      
    5. Now, Assign this image to TabBar's SelectionIndicatorImage

      [tabBar setSelectionIndicatorImage:finalImg];
      

    Swift 4 Version:

    let imgSize = CGSize(width: tabBar.frame.size.width / CGFloat(tabBar.items!.count),
                         height: tabBar.frame.size.height)
    UIGraphicsBeginImageContextWithOptions(imgSize, false, 0)
    let p = UIBezierPath(rect: CGRect(x: 0, y: 0, width: imgSize.width,
                                      height: imgSize.height))
    UIColor.blue.setFill()
    p.fill()
    let finalImg = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    UITabBar.appearance().selectionIndicatorImage = finalImg
    

提交回复
热议问题