SwiftUI:当绑定列表状态改变时,解散视图



我在SwiftUI中有以下示例:

import SwiftUI
struct DetailView: View {
var element:Int
@Binding var favList:[Int]

var body: some View {
Button(action: {
if !favList.contains(element){
favList.append(element)
}
else{
favList.removeAll(where: {$0 == element})
}
}){
HStack {
Image(systemName: (favList.contains(element)) ? "star.slash" : "star")
Text((favList.contains(element)) ? "Remove from favorites" : "Add to favorites")
}
.frame(maxWidth: 300)
}
}
}
struct MainView: View {
let elements = [1,2,3,4]
@State var favList:[Int] = []

var body: some View {
NavigationView {
List{
if !favList.isEmpty{
Section("Favorits"){
ForEach(elements, id: .self){element in
if favList.contains(element){
NavigationLink(destination: DetailView(element: element, favList: $favList)) {
Text("(element)")
}
}
}
}
}
Section("All elements"){
ForEach(elements, id: .self){element in
if !favList.contains(element){
NavigationLink(destination: DetailView(element: element, favList: $favList)) {
Text("(element)")
}
}
}
}

}
}
}
}

如果我在DetailView中更改favList,视图将自动取消。我猜这是因为List结构发生了变化。

我做错了什么吗?这是预期的行为吗?我怎样才能避免这种情况呢?

问好

我尝试过这个,这是相同的代码只是固定的部分标题。在视图中使用fav按钮不会取消视图

import SwiftUI
struct DetailView: View {
var element:Int
@Binding var favList:[Int]

var body: some View {
Button(action: {
if !favList.contains(element){
favList.append(element)
}
else{
favList.removeAll(where: {$0 == element})
}
}){
HStack {
Image(systemName: (favList.contains(element)) ? "star.slash" : "star")
Text((favList.contains(element)) ? "Remove from favorites" : "Add to favorites")
}
.frame(maxWidth: 300)
}
}
}
struct MainView: View {
let elements = [1,2,3,4]
@State var favList:[Int] = []

var body: some View {
NavigationView {
List{
if !favList.isEmpty{
Section(header:Text("Favorits")){
ForEach(elements, id: .self){element in
if favList.contains(element){
NavigationLink(destination: DetailView(element: element, favList: $favList)) {
Text("(element)")
}
}
}
}
}
Section(header:Text("Favorits")){
ForEach(elements, id: .self){element in
if !favList.contains(element){
NavigationLink(destination: DetailView(element: element, favList: $favList)) {
Text("(element)")
}
}
}
}
}
}
}
}

以iOS 14为目标,在xcode 12,5上尝试

最新更新