SwiftUI如何自定义TabItem的Badge颜色?BadgeHub是否支持SwiftUI?
SwiftUI自定义TabItem角标颜色方案说明
BadgeHub适配性结论
- BadgeHub是纯UIKit实现的第三方库,核心是给UIKit体系下的UIView、UIBarButtonItem添加角标能力,没有提供SwiftUI原生的调用接口,无法直接给SwiftUI的TabItem加角标、改颜色。
- 强行使用需要额外编写
UIViewRepresentable包装层桥接UITabBarController,拿到对应UITabBarItem实例后才能调用库方法,代码冗余度高,后续iOS系统版本迭代容易出现布局兼容问题,不推荐使用。
无第三方依赖的原生实现方案
从iOS 15开始,系统原生支持直接自定义TabItem角标的样式,不需要引入任何第三方库,只需要全局配置UITabBarAppearance即可,现有TabView的业务代码不需要做结构性修改。
配置代码直接写在TabView所在页面的初始化方法里即可:
init() { let tabBarAppearance = UITabBarAppearance() let itemAppearance = UITabBarItemAppearance() // 自定义角标背景色 itemAppearance.normal.badgeBackgroundColor = .systemRed // 自定义角标文字颜色、字号 itemAppearance.normal.badgeTextAttributes = [ .foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 12, weight: .medium) ] // 适配不同布局模式下的TabBar tabBarAppearance.stackedLayoutAppearance = itemAppearance tabBarAppearance.inlineLayoutAppearance = itemAppearance tabBarAppearance.compactInlineLayoutAppearance = itemAppearance UITabBar.appearance().standardAppearance = tabBarAppearance if #available(iOS 15.0, *) { UITabBar.appearance().scrollEdgeAppearance = tabBarAppearance } }
配置完成后,原来代码里用.badge()修饰符添加的角标会自动套用自定义的颜色样式。
多Tab角标差异化配色方案
如果需要给不同Tab的角标设置不同颜色,可以在页面出现时拿到对应TabItem单独配置:
// 原有TabView代码 TabView(selection: $selection) { FeaturedView(users: filteredUsers, usersCount: filteredUsersCount) .tabItem { Image(selection == 0 ? "ic_searchFill" : "ic_search").renderingMode(.template) } .tag(0) LikesView(userViews: self.userViews, userLikes: self.userLikes) .tabItem { Image(selection == 1 ? "ic_heartFill" : "ic_heart").renderingMode(.template) } .badge(userLikesCount) .tag(1) ConversationsView(conversations: conversations) .tabItem { Image("ic_chat").renderingMode(.template) } .badge(conversationsCount) .tag(2) SettingsView(user: user) .tabItem { Image(selection == 3 ? "ic_profileFill" : "ic_profile").renderingMode(.template) } .tag(3) } .onAppear { guard let tabBarItems = UITabBar.appearance().items else { return } // 喜欢页角标配粉色 tabBarItems[1].badgeColor = .systemPink // 会话页角标配蓝色 tabBarItems[2].badgeColor = .systemBlue // 可按需修改角标文字属性 tabBarItems[1].setBadgeTextAttributes([.foregroundColor: UIColor.white], for: .normal) tabBarItems[2].setBadgeTextAttributes([.foregroundColor: UIColor.white], for: .normal) }
内容的提问来源于stack exchange,提问作者user14300555
相关产品推荐
相关产品推荐

