不添加视图
self.navigationController?.navigationBar.layer.masksToBounds = false
self.navigationController?.navigationBar.layer.shadowColor = UIColor.lightGray.cgColor
self.navigationController?.navigationBar.layer.shadowOpacity = 0.8
self.navigationController?.navigationBar.layer.shadowOffset = CGSize(width: 0, height: 2.0)
self.navigationController?.navigationBar.layer.shadowRadius = 2
我之前通过在导航栏下方添加视图来完成此操作。
func addShadowToBar() {
let shadowView = UIView(frame: self.navigationController!.navigationBar.frame)
shadowView.backgroundColor = UIColor.whiteColor()
shadowView.layer.masksToBounds = false
shadowView.layer.shadowOpacity = 0.4 // your opacity
shadowView.layer.shadowOffset = CGSize(width: 0, height: 2) // your offset
shadowView.layer.shadowRadius = 4 //your radius
self.view.addSubview(shadowView)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.layer.shadowColor = UIColor.black.cgColor
self.navigationController?.navigationBar.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
self.navigationController?.navigationBar.layer.shadowRadius = 4.0
self.navigationController?.navigationBar.layer.shadowOpacity = 1.0
self.navigationController?.navigationBar.layer.masksToBounds = false
}
如果我没记错的话,默认的导航栏已经带有阴影了。但是,如果您使用 UIView 制作自定义视图,那么您应该这样做以使您的生活更轻松
yourView.clipsToBounds = false
yourView.layer.shadowOffset.height = 5 //this is your offset
yourView.layer.shadowOpacity = 0.25 //opacity of your shadow (recommended)
斯威夫特3:
let shadowView = UIView(frame: navBar.frame)
shadowView.backgroundColor = UIColor.white
shadowView.layer.masksToBounds = false
shadowView.layer.shadowColor = UIColor.lightGray.cgColor
shadowView.layer.shadowOpacity = 0.8
shadowView.layer.shadowOffset = CGSize(width: 0, height: 2.0)
shadowView.layer.shadowRadius = 2
view.addSubview(shadowView)
在 SwiftUI 中,您只需在导航栏正下方添加一个视图即可。
struct ContentView: View {
var body: some View {
NavigationStack {
ScrollView {
VStack(alignment: .leading) {
ForEach(0..<30) { item in
Text("Item \(item)")
.padding()
}
}
.frame(maxWidth: .infinity)
}
.background(
VStack {
Rectangle()
.fill(Gradient(colors: [Color(uiColor: .systemGroupedBackground), .clear]))
.background(Color.clear)
.frame(height: 10)
Spacer()
}
)
.navigationBarTitle("Home", displayMode: .automatic)
.onAppear { UINavigationBar.appearance().shadowImage = .init() }
}
}
}