防止对计算的数组解雇NavigationLink

时间:2020-09-11 19:30:16

标签: swiftui

当显示它的列表重新排序/刷新时,我可以防止解雇NavigationLink吗?

情况

LazyVStack ForEach循环将NavigationLink包装到EditingView中,以获取可识别的Contact对象数组。该数组是一个计算变量,如果.isFavorite == true,则在Contact前面。

在EditingView内部,切换.isFavorite变量将关闭EditingView。即使联系人ID不变,列表也会更改,从而触发重绘。

想法

有没有更聪明的方法?有两件事奏效了:

  1. 不实施收藏夹最喜欢的功能?
  2. 使用VStack而不是LazyVStack(加载时间太长,列表较长)

无效-静态ForEach(切换isFavorite将保持NavLink演示,但切换联系人)

class EditContactsListVM: ObservableObject {
    @Published private var contactStore: ContactStore
    init(_ contactStore: ContactStore) { self.contactStore = contactStore }


    // Static list: no problems with NavigationLink
    var allContacts: [Contact] { contactStore.contacts }


    // Sorted list: toggling .isFavorite triggers NavigationLink dismissal
    var allContactsFrontingAnyFavorites: [Contact] {
        var frontedFavs = [Contact]()
        frontedFavs.append(contentsOf: contactStore.contacts.filter { $0.isFavorite })
        frontedFavs.append(contentsOf: contactStore.contacts.filter { !$0.isFavorite })
        return frontedFavs
    }

}

struct EditContactsListView: View {
    @EnvironmentObject var factory: MainFactory
    @ObservedObject var editList: EditContactsListVM

    init(factory: MainFactory) {
        _editList = ObservedObject(initialValue: factory.makeEditContactsListVM())
    }

    var body: some View {
        ScrollView {
            LazyVStack(alignment: .leading,
                   spacing: .spacingBetweenPrimaryRows) {
                Text(Strings.instructionsEditContactList.local)
                    .padding(.horizontal)
                    .font(.instructions)
                    .foregroundColor(.textInstructions)

                ForEach(editList.allContacts) { contact in
                    NavigationLink(destination: EditContactView(contact, factory)) {
                        ContactRow(contact: contact, toggle: nil)
                    }
                }
            }
            .padding()
        }
        .background(Rectangle()
                        .foregroundColor(.appBackground)
                        .edgesIgnoringSafeArea(.all))
        .navigationBarTitle(Strings.navTitleEditContacts.local, displayMode: .large)
    }
}

0 个答案:

没有答案