查看已接受的答案:SwiftUI 删除导航栏底部边框
import SwiftUI
struct TestView: View {
init(){
let appearance = UINavigationBarAppearance()
appearance.shadowColor = .clear
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
}
var body: some View {
NavigationView{
ScrollView{
ForEach(0 ..< 20){ num in
Text("Num - \(num)")
.padding()
}
}
.navigationTitle("Learn")
}
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView()
}
}
我在使用 UIHostingController 时遇到了同样的问题。所以我最终将一个子 UIHostingController 添加到 UIViewController 并以这种方式设置阴影。
@IBOutlet weak var theContainer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let appearance = UINavigationBarAppearance()
appearance.backgroundColor = UIColor(Color("navbackground"))
appearance.shadowColor = .clear
self.navigationController?.navigationBar.scrollEdgeAppearance = appearance
self.navigationController?.navigationBar.standardAppearance = appearance
let childView = UIHostingController(rootView: SettingsView())
addChild(childView)
childView.view.frame = theContainer.bounds
theContainer.addSubview(childView.view)
childView.didMove(toParent: self)
}
这是 SwiftUI 中隐藏导航栏中底部分隔线的完整工作代码:
let coloredAppearance = UINavigationBarAppearance()
coloredAppearance.configureWithOpaqueBackground()
coloredAppearance.backgroundColor = UIColor(Color.green)
coloredAppearance.titleTextAttributes = [.foregroundColor: UIColor(.white)]
coloredAppearance.largeTitleTextAttributes = [ .foregroundColor: UIColor(.white), .font: UIFont.systemFont(ofSize: 18) ]
coloredAppearance.shadowColor = .clear
coloredAppearance.shadowImage = UIImage()
UINavigationBar.appearance().standardAppearance = coloredAppearance
UINavigationBar.appearance().compactAppearance = coloredAppearance
UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance