swift - SwiftUI VStack 间距:无法正常工作
问题描述
我有一个 SwiftUI VStack,它位于一个滚动视图、一个几何阅读器和一个导航视图内,代码如下:
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
}
}
但无论间距多少,它看起来都是这样的: 图片
但是我注意到当我移动 .navigationBarItems 修饰符时它可以工作,但是一旦你点击 navigationLink 应用程序就会崩溃。
解决方案
SwiftUI
有时在放置一些修饰符时会出现奇怪的行为问题。
就您而言,如果您移至.navigationBarItems
after 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")
}
}
}
}
}
}
}
推荐阅读
- mongodb - 在mongodb中合并子数组
- android - 如何在 android 4.2 中自定义 android action bar?
- tensorflow - model.execute(dict)中提供的dict['ToFloat']的shape必须是[]
- url - 如何在 VS Code 中更改 LocalHost URL
- audio - 如何在 Ffmpeg 中将音频速度设置为 0.3?
- gnuradio - 如何在 GNU-radio 中设置 USRP 天线
- excel - VBA正则表达式反向查找特殊字符
- wpf - 如何在wpf中删除anchorItem
- r - 运行回归,其中整个列在 R 中包含 NA
- python - 如何从数据框上的文本字段中删除松散的字母