ios - 快速错误: "Type ' ( )' cannot conform to ' View'; only struct/enum/class types can conform to protocols"when calling function to write text

标签 ios swift swiftui

我正在尝试使用完成来写入文本,但当我尝试运行时收到错误“类型'()'不能符合' View ';只有结构/枚举/类类型可以符合协议(protocol)”它。任何帮助都会很棒,谢谢!

VStack {
                    Image("external_white")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 60, height: 60.0)
                    Text("External IP")
                    getExternalAddress("") { (test) -> Any in
                        Text(test)
                    }
                }

调用的函数:

func getExternalAddress(_ key: String, completion: @escaping (String) -> Any) {
    var test = key
    Ipify.getPublicIPAddress { result in
        switch result {
        case .success(let ip):
            print(ip + " ip") // "210.11.178.112"
            test = ip
            print(test + " test")
            completion(test)
        case .failure(let error):
            print(error.errorDescription)
        }
    }

最佳答案

您不应该尝试在 View 中执行所有操作,SwiftUI 引入了多种在对象之间发布数据的方法,因此请使用它。

在此示例中,我将您的函数移至另一个可以观察并发布找到的 IP 地址的类

class IpFinder: ObservableObject {
    @Published var ipAddress: String = ""

    func getExternalAddress(_ key: String) {
        var test = key
        Ipify.getPublicIPAddress { result in
            switch result {
            case .success(let ip):
                ipAddress = ip
            case .failure(let error):
                print(error.errorDescription)
            }
        }
    }
}

然后在您的 View 中观察此类的实例

struct ContentView: View {
    @ObservedObject var ipFinder: IPFinder = IPFinder()
    @State var value = 0
    @State private var key = ""

    var body: some View {
        VStack {
            Image("external_white")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 60, height: 60.0)
            Text("External IP")

            Text(ipFinder.ipAddress)

            TextField("key", text:$key)

            Button(action: {
                ipFinder.getExternalAddress(key)
            }, label: {
                Text("Get IP address")
            })
        }
    }
}

关于ios - 快速错误: "Type ' ( )' cannot conform to ' View'; only struct/enum/class types can conform to protocols"when calling function to write text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64862835/

相关文章:

ios - UIActivityIndi​​catorView startAnimating 在 searchBarSearchButtonClicked 中不起作用

ios - 在 Swift 中使用 Hashable 扩展 @objc 协议(protocol)

swift - 如何将数字添加到始终使用两个字符表示的字符串?

ios - 如何从认知用户 ID 中删除外部身份并检查当前认知 ID 是否与任何外部身份合并?

xcode - 快速连接到网络 smb 驱动器

ios - 组合:监听内部集合变化

ios - ScrollView 内容未填充 SwiftUI

ios - 将 NSDate 转换为另一种格式

ios - 问题 找不到自动链接框架 'FirebaseMessaging'

swiftui - 当我的 @Published NSManagedObjects 数组更改时,我的 SwiftUI 列表不会更新