NavigationView 为我们提供了页面导航
NavigationLink 提供跳转功能
基本用法
import SwiftUI
struct cellModel:Identifiable {
var id = UUID()
var name:String
var desc:String
}
struct cell: View {
var model:cellModel
var body: some View {
VStack (alignment: .leading) {
Text(model.name)
.fontWeight(.bold)
.padding(10)
Text(model.desc)
}
}
}
struct ContentView: View {
var cells = [cellModel(name: "1", desc: "111"),
cellModel(name: "2", desc: "22222222222222"),
cellModel(name: "3", desc: "33333333"),
cellModel(name: "4", desc: "4444")
]
var body: some View {
NavigationView {
List(cells) { item in
NavigationLink {
detailView(text: item.desc)
.navigationBarTitle("Detail",displayMode: .inline)
} label: {
cell(model: item)
}
}
.listStyle(.plain)
.navigationBarTitle("导航栏",displayMode: .inline)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
设置字体颜色 更换返回按钮图片
在ContentView 内实现init方法
struct ContentView: View {
var cells = [cellModel(name: "1", desc: "111"),
cellModel(name: "2", desc: "22222222222222"),
cellModel(name: "3", desc: "33333333"),
cellModel(name: "4", desc: "4444")
]
var body: some View {
NavigationView {
List(cells) { item in
NavigationLink {
detailView(text: item.desc)
.navigationBarTitle("Detail",displayMode: .inline)
} label: {
cell(model: item)
}
}
.listStyle(.plain)
.navigationBarTitle("导航栏",displayMode: .inline)
}
}
init() {
//修改导航栏文字颜色
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.red, .font: UIFont(name: "ArialRoundedMTBold", size: 35)!]
navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.red, .font: UIFont(name: "ArialRoundedMTBold", size: 20)!]
//修改按钮图片
navBarAppearance.setBackIndicatorImage(UIImage(systemName: "arrow.turn.up.left"), transitionMaskImage: UIImage(systemName: "arrow.turn.up.left"))
//修改渲染颜色 Xcode14.2 未生效
UINavigationBar.appearance().tintColor = .black
UINavigationBar.appearance().standardAppearance = navBarAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance
UINavigationBar.appearance().compactAppearance = navBarAppearance
}
}
自定义返回按钮
1.navigationBarBackButtonHidden() 隐藏导航栏
2.navigationBarItems 自定义按钮
import SwiftUI
struct detailView: View {
@Environment(\.dismiss) var dismiss
var text:String = ""
var body: some View {
Text(text)
.navigationBarBackButtonHidden()
.navigationBarItems(leading: Button(action: {
dismiss()
}, label: {
HStack{
Text("\(Image(systemName: "chevron.left")) \(text)")
.foregroundColor(.black)
}
}))
}
}
struct detailView_Previews: PreviewProvider {
static var previews: some View {
detailView()
}
}