当显示它的列表重新排序/刷新时,我可以防止解雇NavigationLink吗?
LazyVStack ForEach循环将NavigationLink包装到EditingView中,以获取可识别的Contact对象数组。该数组是一个计算变量,如果.isFavorite == true,则在Contact前面。
在EditingView内部,切换.isFavorite变量将关闭EditingView。即使联系人ID不变,列表也会更改,从而触发重绘。
有没有更聪明的方法?有两件事奏效了:
无效-静态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)
}
}