swift - 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)")
}
}
}
}
}
}
}
}
如果我在视图中更改,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 上进行了尝试
推荐阅读
- ios - 如何在 iOS 中拨打电话时隐藏 *DTMF* 号码
- c++ - 以下代码使用构造函数对字符串进行排序有什么问题?
- reactjs - 如何在 ReactTable V7 中管理 noDataComponent 或显示未找到的行
- amazon-web-services - 将 Kong 与 AWS EKS 结合使用
- python - flask-migrate:在迁移中运行自定义 SQL?
- javascript - JavaScript 正在返回一个重复的小数
- odoo-13 - 什么是 context_today?
- ubuntu - Ansible 出现奇怪的文件权限/身份验证错误
- javascript - 动态生成一个
- 从 Javascript 中的输入数组中列出
- python - 如何将带有 .Net 应用程序的 Python 作为一个安装可执行文件分发?