在 swift 中将阴影应用到导航栏

问题描述 投票:0回答:6

在我的应用程序设计导航中有很好的阴影,我想在我的代码中应用。 我怎样才能创造出这种效果?

ios swift
6个回答
50
投票

不添加视图

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

5
投票

我之前通过在导航栏下方添加视图来完成此操作。

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)
}

3
投票
    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
}

2
投票

如果我没记错的话,默认的导航栏已经带有阴影了。但是,如果您使用 UIView 制作自定义视图,那么您应该这样做以使您的生活更轻松

yourView.clipsToBounds = false
yourView.layer.shadowOffset.height = 5 //this is your offset
yourView.layer.shadowOpacity = 0.25 //opacity of your shadow (recommended)

1
投票

斯威夫特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)

0
投票

在 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() }
    }
}

}

© www.soinside.com 2019 - 2024. All rights reserved.