问题描述
我在 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)")
}
}
}
}
}
}
}
}
如果我更改 favList
中的 DetailView
,视图会自动关闭。我猜这是因为 List
结构发生了变化。
我做错了吗?这是预期的行为吗?我怎样才能避免这种情况?
最好的问候
解决方法
我试过这个,它是相同的代码,只是修复了部分标题。在视图中使用收藏按钮不会关闭视图
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 上进行了尝试