SwiftUI ForEach用于预览和打印设备名称

时间:2020-02-06 04:24:08

标签: swift swiftui

我正在尝试在生成用于预览的SiftUI时打印设备名称。

以下代码完全可以正常工作。

struct LandmarkList_Previews: PreviewProvider {
    static var previews: some View {

        ForEach(["iPhone SE","iPhone 11 Pro Max","iPhone SE"], id: \.self) { (deviceName)  in

            LandmarkList().previewDevice(PreviewDevice(rawValue: deviceName))
        }
    }
}

在生成预览时如何打印设备名称。好像print不能写在这个闭包中。下面是无效的代码

struct LandmarkList_Previews: PreviewProvider {
    static var previews: some View {

        ForEach(["iPhone SE","iPhone 11 Pro Max","iPhone SE"], id: \.self) { (deviceName)  in
          print("device name\(deviceName)")
            return LandmarkList().previewDevice(PreviewDevice(rawValue: deviceName))
        }
    }
}

2 个答案:

答案 0 :(得分:0)

打印在这里不起作用。您宁可只采用这种方式进行调试

    let deviceArray = ["iPhone SE","iPhone 11 Pro Max","iPhone SE"]


    VStack(){
        ForEach(self.deviceArray, id: \.self) { deviceName in
          Text(deviceName) // for debugging purpose
            return LandmarkList().previewDevice(PreviewDevice(rawValue: deviceName))
        }

    }

请参阅以下内容以更好地理解

Array.forEach creates error "Cannot convert value of type '()' to closure result type '_'"

答案 1 :(得分:0)

这是一个有效的代码

static var previews: some View {
    ForEach(["iPhone SE","iPhone 11 Pro Max","iPhone SE"], id: \.self) { deviceName -> AnyView in
        print("device name\(deviceName)")
        return AnyView(TestPublishBridging().previewDevice(PreviewDevice(rawValue: deviceName)))
    }
}