如何实现适配Table View Cell的透明导航栏 解决单元格重叠与导航栏变黑问题
解决方案
两种可落地的实现方式,均可以保留导航栏透明效果,同时避免单元格被遮挡:
方案1:保持Extend Edges默认配置,调整TableView约束
这个是兼容性最高的方案,不需要修改导航栏默认行为:
- 打开Storyboard/XIB,选中当前ViewController的TableView
- 把TableView的顶部约束从
superview.top修改为对齐Safe Area.top - 运行即可看到单元格从导航栏下方开始显示,导航栏透明效果保留
如果是纯代码布局,添加约束时指定顶部参照:
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
方案2:关闭Under Top Bars,使用新版导航栏外观API修复黑栏问题
关闭Under Top Bars后导航栏变黑的原因是:半透明导航栏默认会透出下方的视图内容,view不延伸到导航栏下方时,导航栏没有下层内容可透就会显示为黑色。你之前的代码不生效是因为iOS 13及以上版本需要使用UINavigationBarAppearance配置导航栏样式,旧属性优先级更低。
在viewDidLoad中添加如下代码即可:
if #available(iOS 13.0, *) { let navAppearance = UINavigationBarAppearance() // 配置为透明背景 navAppearance.configureWithTransparentBackground() // 可选:隐藏导航栏底部分割线 navAppearance.shadowColor = .clear // 同时赋值给两种状态的外观,滚动时也会保持透明 navigationController?.navigationBar.standardAppearance = navAppearance navigationController?.navigationBar.scrollEdgeAppearance = navAppearance } else { // iOS13以下的兼容写法 navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.isTranslucent = true }
内容的提问来源于stack exchange,提问作者Helga
相关产品推荐
相关产品推荐

