【问题标题】:Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols类型 '()' 不能符合 'View';只有结构/枚举/类类型可以符合协议
【发布时间】:2020-11-10 00:05:33
【问题描述】:

我目前正在学习 swift,我正在尝试制作一个简单的应用程序来显示您是否已连接到互联网,但我不断收到以下错误:

类型'()'不能符合'View';只有结构/枚举/类类型可以符合协议

这是代码:

struct ContentView: View {
    
    let NetworkMonitor = NWPathMonitor(requiredInterfaceType: .wifi)
    
    var body: some View {
        
        VStack {                                        //Line with the error
        
            Text("Network Check")
            
            NetworkMonitor.pathUpdateHandler = {path in
                if path.status == .satisfied {
                    Text("We are Connected")
                } else {
                    Text("We are not connected")
                }
            }
        }
    }
}

我曾尝试删除 VStack 和“网络检查”文本,但它在 var body: some View 行上发送另一个错误:

函数声明了一个不透明的返回类型,但它的主体中没有返回语句来推断基础类型

谢谢

【问题讨论】:

  • 错误在NetworkMonitor.pathUpdateHandler =,不允许在视图构建器块中使用表达式,只能在视图中使用。回调内部的视图(在这种情况下为文本)什么也不做,因为它们是视图。阅读@State 以及如何更新视图。

标签: ios swift xcode swiftui


【解决方案1】:

由于您正在调用一个函数,因此您无法在视图构造中执行此操作,请尝试在 onAppear 中调用它:

struct ContentView: View {

 let NetworkMonitor = NWPathMonitor(requiredInterfaceType: .wifi)
    @State var status = false
    var body: some View {
        VStack {
            Text("Network Check")
            if status {
                Text("We are Connected")
            } else {
                Text("We are not connected")
            }
            
        }.onAppear() {
           NetworkMonitor.pathUpdateHandler = { path in
            self.status = path.status == .satisfied
            }
        }
    }


}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多