有一个工具栏按钮可以更改 ContentView 中的 viewStyle。
当viewStyle改变时,MyPage会根据viewStyle重新生成List。但是,生成后,这个List与navigationTitle之间的距离会自动增加。另外,navigationTitle 原本是随 List 一起滚动的,但更改 viewStyle 后,它会保持静止。
出了什么问题? 谢谢。
import SwiftUI
struct ContentView: View {
@State private var viewStyle: ViewStyle = .bold
var body: some View{
NavigationView {
TabView {
MyPage(viewStyle: $viewStyle)
.tabItem {
Label("Today", systemImage: "1.square.fill")
}
.tag(0)
}
.navigationTitle("title")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
viewStyle = viewStyle.next
}) {
Image(systemName: "pencil")
}
}
}
}
}
}
struct MyPage: View {
@Binding var viewStyle: ViewStyle
var body: some View {
switch viewStyle {
case .bold:
List{
ForEach(0..<4, id: \.self){ index in
VStack{
Label("bold", systemImage: "pencil")
}
}
}
default:
List{
ForEach(0..<3, id: \.self){ index in
VStack{
Label("italic", systemImage: "pencil")
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
enum ViewStyle{
case bold
case italic
var next: ViewStyle{
switch self {
case .bold: return .italic
case .italic: return .bold
}
}
}
更换
List
时会发生这种情况。尝试保留 List
并仅替换内容:
struct MyPage: View {
@Binding var viewStyle: ViewStyle
var body: some View {
List { // 👈 Move this out here
switch viewStyle {
case .bold:
ForEach(0..<4, id: \.self){ index in
VStack{
Label("bold", systemImage: "pencil")
}
}
default:
ForEach(0..<3, id: \.self){ index in
VStack{
Label("italic", systemImage: "pencil")
}
}
}
}
}
}
注意:始终尝试最小化更改,以防止意外的渲染和行为。例如,您可以只更改
title
和 count
而不是整个列表!