我有一个 SwiftUI 列表,它在点击单元格时显示详细视图/推送到导航:
import SwiftUI
struct DevicesInRangeList: View {
@ObservedObject var central = Central()
var body: some View {
NavigationView {
List(central.peripheralsInRange) { peripheral in
NavigationLink(destination: DeviceView(peripheral: peripheral).onAppear {
self.central.connect(peripheral: peripheral)
}.onDisappear {
self.central.disconnect(peripheral: peripheral)
}) {
DeviceRow(deviceID: peripheral.deviceID, name: peripheral.name)
}
}.onAppear {
self.central.scanning = true
}.onDisappear {
self.central.scanning = false
}.navigationBarTitle("Devices in range")
}
}
}
如果我点击一行,则会显示详细信息。如果外围设备断开连接,它将从 peripheralsInRange 数组中删除,并且该行被删除——但仍会显示详细信息。删除关联行时如何删除详细信息?
编辑:在 Asperi 的回答之后,我有以下内容,但仍然无法正常工作:
struct DevicesInRangeList: View {
@ObservedObject var central = Central()
@State private var localPeripherals: [Peripheral] = []
@State private var activeDetails = false
var body: some View {
NavigationView {
List(localPeripherals, id: \.self) { peripheral in
NavigationLink(destination:
DeviceView(peripheral: peripheral)
.onReceive(self.central.$peripheralsInRange) { peripherals in
if !peripherals.contains(peripheral) {
self.activeDetails = false
}
}
.onAppear {
self.central.connect(peripheral: peripheral)
}
.onDisappear {
self.central.disconnect(peripheral: peripheral)
}
, isActive: self.$activeDetails) {
DeviceRow(deviceID: peripheral.deviceID, name: peripheral.name)
}
}.onReceive(central.$peripheralsInRange) { peripherals in
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.localPeripherals = peripherals
}
}.onAppear {
self.central.scanning = true
self.localPeripherals = self.central.peripheralsInRange
}.onDisappear {
self.central.scanning = false
}.navigationBarTitle("Devices in range")
}
}
}