如何通过声明枚举为不同用户类型设置App导航栏与TabBar颜色
当然可以用枚举来实现!这种方式比到处写if判断要优雅得多,还能让用户类型和对应UI颜色的绑定关系更清晰。我给你分享两种实用的实现思路:
方法一:用户类型枚举 + 颜色配置结构体
先定义明确的用户类型枚举,再让颜色结构体根据用户类型返回对应配色:
// 第一步:定义用户类型枚举 enum UserType { case admin case normalUser } // 第二步:修改颜色配置结构体,添加按用户类型返回颜色的方法 struct AppColor { struct NavigationBar { static func tintColor(for userType: UserType) -> UIColor { switch userType { case .admin: return UIColor(red: 0.01, green: 0.54, blue: 0.16, alpha: 1.0) // 管理员专属绿色 case .normalUser: return UIColor(red: 0.2, green: 0.4, blue: 0.8, alpha: 1.0) // 普通用户专属蓝色 } } static func textColor(for userType: UserType) -> UIColor { // 如果两种用户的文本颜色一致,直接返回统一值;需要区分的话再加switch即可 return .white } } struct TabBar { static func tintColor(for userType: UserType) -> UIColor { switch userType { case .admin: return UIColor(red: 0.0, green: 0.6, blue: 0.2, alpha: 1.0) case .normalUser: return UIColor(red: 0.3, green: 0.5, blue: 0.9, alpha: 1.0) } } } }
调用的时候只需要传入当前用户类型,代码会自动匹配对应颜色:
// 假设你已经通过登录逻辑获取到当前用户类型 let currentUserType: UserType = .admin // 给TabBar设置颜色 tabBarController.tabBar.barTintColor = AppColor.TabBar.tintColor(for: currentUserType) // 给NavigationBar设置颜色和文本色 navigationController?.navigationBar.tintColor = AppColor.NavigationBar.tintColor(for: currentUserType) navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: AppColor.NavigationBar.textColor(for: currentUserType)]
方法二:将颜色直接绑定到用户类型枚举的关联属性
这种方式更紧凑,把每种用户类型对应的所有UI颜色都封装在枚举内部,调用起来更直观:
enum UserType { case admin case normalUser // 导航栏 tint 颜色 var navigationBarTintColor: UIColor { switch self { case .admin: return UIColor(red: 0.01, green: 0.54, blue: 0.16, alpha: 1.0) case .normalUser: return UIColor(red: 0.2, green: 0.4, blue: 0.8, alpha: 1.0) } } // 导航栏文本颜色 var navigationBarTextColor: UIColor { return .white } // TabBar 颜色 var tabBarTintColor: UIColor { switch self { case .admin: return UIColor(red: 0.0, green: 0.6, blue: 0.2, alpha: 1.0) case .normalUser: return UIColor(red: 0.3, green: 0.5, blue: 0.9, alpha: 1.0) } } }
调用时直接访问枚举实例的属性即可,非常简洁:
let currentUserType: UserType = .normalUser tabBarController.tabBar.barTintColor = currentUserType.tabBarTintColor navigationController?.navigationBar.tintColor = currentUserType.navigationBarTintColor navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: currentUserType.navigationBarTextColor]
两种方案都能有效避免零散的if判断,后续如果新增用户类型,只需要在枚举里补充case和对应的颜色配置就行,维护起来特别方便。
内容的提问来源于stack exchange,提问作者Emre Önder
相关产品推荐
相关产品推荐

