我有一个SwiftUI VStack,它位于scrollView,Geometry阅读器和NavigationView中,这是代码:
struct RezeptList: View {
@Environment(\.colorScheme) var colorScheme: ColorScheme
@EnvironmentObject private var recipeStore: RecipeStore
@State private var searching = false
@State private var searchText = ""
@State private var showingAddRecipeView = false
var body: some View {
NavigationView{
GeometryReader { geo in
ScrollView {
SearchBar(searchText: self.$searchText, isSearching: self.$searching)
VStack(spacing: 30) {
ForEach(self.recipeStore.recipes.filter{$0.name.hasPrefix(self.searchText) || self.searchText == ""}) {recipe in
NavigationLink(destination:
RezeptDetail(recipe: recipe).environmentObject(self.recipeStore)) {
Card(rezept: recipe,width: geo.size.width - 20)
}
.buttonStyle(PlainButtonStyle())
}
.navigationBarItems(trailing: Button(action: {
self.showingAddRecipeView = true
}){
Image(systemName: "square.and.pencil")
.foregroundColor(.primary)
}
.padding()
)
}
.padding(.bottom)
.navigationBarTitle("Rezepte")
.sheet(isPresented: self.$showingAddRecipeView) {
AddRecipeView(isPresented: self.$showingAddRecipeView)
.environmentObject(self.recipeStore)
}
}
}
}
}
init() {
UINavigationBar.appearance().tintColor = UIColor.label
}
}
但是无论间距多少,它看起来都是这样: Image
但是我注意到,当我移动.navigationBarItems修改器时,它可以工作,但是一旦您点击navigationLink,应用就会崩溃。
答案 0 :(得分:1)
SwiftUI
有时在放置某些修饰符时出现奇怪的行为问题。
对于您而言,如果将.navigationBarItems
移到navigationBarTitle
之后,它将解决此问题,并且您将获得VStack
的间距。
.navigationBarTitle("Rezepte")
.navigationBarItems(trailing: Button(action: {
self.showingAddRecipeView = true
}, label: {
Image(systemName: "square.and.pencil")
.foregroundColor(.primary)
}).padding())
此外,我观察到,与导航相关的修饰符更靠近NavigationView
而不是层次结构中的深度更好。
struct ContentView: View {
@State var isShowing: Bool = false
var body: some View {
NavigationView {
GeometryReader { (geo) in
ScrollView {
VStack(spacing: 60) {
ForEach(0...10, id:\.self) { (index) in
NavigationLink(destination: Text(String(index))) {
Text("Button")
}
}
}
.navigationBarTitle("Title")
.navigationBarItems(trailing: Button(action: {
self.isShowing = true
}, label: {
Image(systemName: "square.and.pencil")
}))
.sheet(isPresented: self.$isShowing) {
Button(action: {
self.isShowing = false
}) {
Text("Dismiss")
}
}
}
}
}
}
}