Home > Software design >  Setting tabBarAppearance makes it so UITabBarItem doesn't respect `imageInsets`
Setting tabBarAppearance makes it so UITabBarItem doesn't respect `imageInsets`

Time:12-29

When I set the UITabBar's appearance, it makes it so the UITabBarItem's imageInsets and titlePositionAdjustment aren't respected anymore on iOS 15. Removing the line [UITabBar appearance].standardAppearance = tabBarAppearance; makes it so the image and label lineup but the background color can't be set. Has anyone run into something like this and solved it?

Code:

UITabBarAppearance *tabBarAppearance = [[UITabBarAppearance alloc] init];
[tabBarAppearance configureWithOpaqueBackground];
[UITabBar appearance].standardAppearance = tabBarAppearance;
[UITabBar appearance].scrollEdgeAppearance = tabBarAppearance;

static let tabBarImageInsets: UIEdgeInsets = UIEdgeInsets(top: 4.0, left: 0, bottom: -4.0, right: 0)
static let titlePositionAdjustmentValue: UIOffset = UIOffset(horizontal: 0.0, vertical: -8.0)
tabBarItem.imageInsets = tabBarImageInsets
tabBarItem.titlePositionAdjustment = titlePositionAdjustmentValue

Images:

Tab Bar with appearance and misaligned label

Tab Bar without appearance, properly aligned label and image, and no background

CodePudding user response:

I solved this after actually reading the Apple docs:

if (@available(iOS 15.0, *)) {
        UINavigationBarAppearance *navBarAppearance = [[UINavigationBarAppearance alloc] init];
        [navBarAppearance configureWithOpaqueBackground];
        [UINavigationBar appearance].standardAppearance = navBarAppearance;
        [UINavigationBar appearance].compactAppearance = navBarAppearance;
        [UINavigationBar appearance].scrollEdgeAppearance = navBarAppearance;

        UITabBarAppearance *tabBarAppearance = [[UITabBarAppearance alloc] init];
        [tabBarAppearance configureWithOpaqueBackground];
        [UITabBar appearance].standardAppearance = tabBarAppearance;
        [UITabBar appearance].scrollEdgeAppearance = tabBarAppearance;

        UITabBarItemAppearance *tabBarItemAppearance = [[UITabBarItemAppearance alloc] init];

        tabBarItemAppearance.normal.titleTextAttributes = [[RRUIDesignToken.font nav] makeTextAttributes];
        if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
            tabBarItemAppearance.normal.titlePositionAdjustment = UIOffsetMake(0.0, -[RRUIDesignToken.size paddingXsmall]);
        } else {
            tabBarItemAppearance.normal.titlePositionAdjustment = UIOffsetMake(0.0, -[RRUIDesignToken.size paddingXxsmall]);
        }

        tabBarAppearance.stackedLayoutAppearance = tabBarItemAppearance;
        tabBarAppearance.compactInlineLayoutAppearance = tabBarItemAppearance;
        tabBarAppearance.inlineLayoutAppearance = tabBarItemAppearance;
    }
  • Related