我的SwiftUI代码导致一个大的空白窗口



所以我一直在开发一个应用程序来在Mac上重新创建iOS电池小部件,但我所有的努力都导致了一个空白屏幕。这是我的代码,任何帮助都是感激的。

我尝试了各种不同的方法,包括LazyVGrid,但无济于事。

非常感谢你看一眼,希望你有一个美好的一天!

ContentView.swift

struct ContentView: View {
@State var devices: [Device] = [
Device(name: "Mark's Mac Book pro", type: .macbook, level: 1.00),
Device(name: "MX Master 2S", type: .mouse, level: 0.75),
Device(name: "MX Keys", type: .keyboard, level: 0.50),
Device(name: "Mark's Airpods Max", type: .airpodsMax, level: 0.63)
]
@State var size: Double = 150.00
var body: some View {
ScrollView {
BatteryGrid(devices: $devices, size: $size)
}
.frame(minWidth: 300, minHeight: 175)
}
}

BatterGrid.swift

struct BatteryGrid: View {
@Binding var devices: [Device]
@Binding var size: Double
@State var count = 0
@ObservedObject var deviceArrays = PublishedDevices()
@State var devicesPerRow = 0
@State var rows = 0
@State var currentDevice = Device()
var body: some View {
VStack {
GeometryReader { geometry in
ForEach(deviceArrays.devices, id: .id) { deviceArray in
HStack {
ForEach(deviceArray.row, id: .id) { device in
Progresso(device: $currentDevice, size: $size)
.onAppear {
setCurrentDevice(to: device)
}
}
}
}
.onAppear {
devicesPerRow = Int(geometry.size.width.rounded(.up)) / Int(size.rounded(.down))
rows = devices.count / devicesPerRow
}
}
}
}
func setCurrentDevice(to device: Device) {
currentDevice = device
}
}
struct DeviceRow: Identifiable {
var row: [Device] = []
var id = UUID()
}
class PublishedDevices: ObservableObject {
@Published var devices: [DeviceRow] = []
}

最后是Progresso.swift

struct Progresso: View {
@Binding var device: Device
@Binding var size: Double
var body: some View {
ZStack {
Circle()
.stroke(lineWidth: 8)
.frame(maxWidth: .infinity)
.frame(height: 100)
.foregroundColor(.gray)
.opacity(0.30)
Circle()
.trim(from: 0.0, to: device.level ?? 0)
.stroke(style: StrokeStyle(lineWidth: 8, lineCap: .round, lineJoin: .round))
.frame(maxWidth: .infinity)
.frame(height: 100)
.foregroundColor((device.level ?? 0) > 0.20 ? .green : .red)
.rotationEffect(Angle(degrees: 270.0))
VStack {
device.icon()
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 40, height: 40)
Text("(Int(((device.level ?? 0) * 100).rounded(.up)))%")
.font(.body.bold())
.frame(width: 75)
.lineLimit(1)
}
}
}
}

视图是空白的,因为您遍历了一个空数组deviceArrays.devices

class PublishedDevices: ObservableObject {
@Published var devices: [DeviceRow] = []
}

另外,在您的BatteryGrid结构体中,当您将PublishedDevices声明为@ObservedObject时。它作为视图的真实来源,因此必须将其声明为@StateObject

@ObservedObject在你传递一个真实源(视图模型)给另一个视图时使用

关于状态对象的更多信息在这里https://developer.apple.com/documentation/swiftui/stateobject

最新更新