You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI TabView结合Realm:首尾元素删除功能异常问题

问题描述
  • 我们使用Realm数据库,包含Album对象,Album下关联Item列表。
  • 在TabView中打开Album,可滚动浏览并删除Item,且能从任意Item直接打开TabView(比如点击3,打开的TabView当前项就是3),这部分功能正常。

删除Item时的异常问题
仅当从列表末尾(当前索引4)或开头(当前索引0)打开TabView,且未进行滚动操作就立即删除当前项时,TabView不会更新当前选中元素(绑定的$current),onChange事件也不会触发。

请问这是操作错误,还是TabView的bug?

import SwiftUI
import RealmSwift

final class Album: Object, ObjectKeyIdentifiable {
    @Persisted(primaryKey: true) var _id: ObjectId
    @Persisted var items = RealmSwift.List<Item>()
}

final class Item: Object, ObjectKeyIdentifiable {
    @Persisted(primaryKey: true) var _id: ObjectId
    @Persisted(originProperty: "items") var album: LinkingObjects<Album>
    @Persisted var label: String
}

func genAlbum () -> Album {
    let realm = try! Realm()
    let album = Album()
    try! realm.write {
        album.items.append(Item(value: ["label": "0"]))
        album.items.append(Item(value: ["label": "1"]))
        album.items.append(Item(value: ["label": "2"]))
        album.items.append(Item(value: ["label": "3"]))
        album.items.append(Item(value: ["label": "4"]))
        realm.add(album)
    }
    print(album)
    return album
}

let albumStore = genAlbum()


struct ContentView: View {
    @ObservedRealmObject var album = albumStore
    @State private var selectedItem: Item?
    var body: some View {
        VStack {
            Text("Count: \(self.album.items.count)")
            HStack (spacing: 10) {
                ForEach(self.album.items, id: \._id) { item in
                    Button(action: { self.selectedItem = item },
                        label: { Text("\(item.label)")
                                .font(.largeTitle)
                                .tag(item)
                        }
                    )
                        .buttonStyle(.bordered)
                        .fullScreenCover(item: self.$selectedItem, content: {
                        currentItem in
                        AlbumView(album: self.album, current: currentItem, onDismiss: { self.selectedItem = nil })
                            .background(.blue)
                            .padding()
                    })
                }
            }
        }
    }
}



struct AlbumView: View {
    @ObservedRealmObject var album: Album
    @State var current: Item
    var onDismiss: (() -> Void)? = nil

    var body: some View {
        TabView(selection: $current) {
            ForEach(self.album.items, id: \._id) { item in
                Text(item.label)
                    .font(.largeTitle)
                    .tag(item)
                    .background(.red)
                    .padding()
            }
        }
            .tabViewStyle(.page(indexDisplayMode: .never))
            .onChange(of: current) { oldCurrent, newCurrent in
            print("::::onChange current", oldCurrent.label, newCurrent.label)
        }
            .overlay(

            VStack {
                Spacer()
                HStack {
                    let i = album.items.index(of: current)
                    Text ("overlay tab current item :\(current.label) \(i ?? -1)")
                    if let index = album.items.index(of: current) {
                        Button(action: {
                            print("Delete \(index)")
                            $album.items.remove(at: index)
                            print("Items count \($album.items.count)")
                            print("Indexes \($album.items.indices)")
                        },
                            label: {
                                Text("Delete label:\(current.label)  index \(index)") }
                        ).padding().background(.red)
                    }
                    Spacer()
                    Button(action: {
                        if let dismiss = self.onDismiss {
                            dismiss()
                        } }, label: { Text("Close") })
                        .padding().background(.red)

                }
            }
        )

    }
}

问题演示截图

内容的提问来源于stack exchange,提问作者Олег Мосейко

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 06:49:57