如何为自定义UITabBarController配置scrollEdgeAppearance并保持样式禁用透明
解决方案
要解决滚动时TabBar变透明的问题,核心是统一配置standardAppearance和scrollEdgeAppearance,让两种状态下的样式保持一致,同时适配你自定义的CAShapeLayer效果:
修改你的configureTabbar方法,补充以下配置:
func configureTabbar() { // 1. 创建统一的TabBar外观配置实例 let tabBarAppearance = UITabBarAppearance() // 将背景设为透明,避免覆盖自定义的CAShapeLayer tabBarAppearance.backgroundEffect = nil tabBarAppearance.backgroundColor = .clear // 配置选中状态的图标/文字颜色(与原有设置对齐) tabBarAppearance.stackedLayoutAppearance.selected.iconColor = AppColors.tabbarTintColor tabBarAppearance.stackedLayoutAppearance.selected.titleTextAttributes = [.foregroundColor: AppColors.tabbarTintColor] // 若有未选中状态的样式需求,补充以下配置 // tabBarAppearance.stackedLayoutAppearance.normal.iconColor = 你的未选中图标颜色 // tabBarAppearance.stackedLayoutAppearance.normal.titleTextAttributes = [.foregroundColor: 你的未选中文字颜色] // 2. 同时配置两种外观,确保滚动状态样式一致 tabBar.standardAppearance = tabBarAppearance // iOS 15+ 需单独配置scrollEdgeAppearance,解决滚动到顶部时的透明问题 if #available(iOS 15.0, *) { tabBar.scrollEdgeAppearance = tabBarAppearance } // --- 你原有的自定义TabBar代码保持不变 --- UITabBar.appearance().tintColor = AppColors.tabbarTintColor let cornerRadius: CGFloat = 15 let layer = CAShapeLayer() layer.path = UIBezierPath(roundedRect: CGRect(x: 45, y: self.tabBar.bounds.minY - 10, width: self.tabBar.bounds.width - 90, height: self.tabBar.bounds.height + 10), cornerRadius: cornerRadius).cgPath layer.shadowColor = UIColor.lightGray.cgColor layer.shadowOffset = CGSize(width: 5.0, height: 5.0) layer.shadowRadius = 25.0 layer.shadowOpacity = 0.3 layer.borderWidth = 1.0 layer.opacity = 1.0 layer.isHidden = false layer.masksToBounds = false layer.fillColor = AppColors.tabbarBG.cgColor self.tabBar.layer.insertSublayer(layer, at: 0) if let items = self.tabBar.items { items.forEach { item in item.imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: -15, right: 0) } } self.tabBar.itemWidth = 30.0 self.tabBar.itemPositioning = .centered }
关键说明:
- 将外观的
backgroundColor设为.clear,是为了让你手动添加的CAShapeLayer能正常显示,不会被系统默认的背景层覆盖 - 同时设置
standardAppearance和scrollEdgeAppearance,确保滚动到顶部时TabBar的样式与普通状态完全一致 - 原代码中
UITabBar.appearance().backgroundColor可移除,避免与新的外观配置产生冲突
内容的提问来源于stack exchange,提问作者Thush-Fdo
相关产品推荐
相关产品推荐

