我正在尝试使用完成来写入文本,但当我尝试运行时收到错误“类型'()'不能符合' 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/