繁体   English   中英

SwiftUI:如何在 ContentView 中调用 function?

[英]SwiftUI: How to call a function in ContentView?

我正在尝试调用一个 function ,它接受一个值并输出一个字符串。 但是,内容视图中的代码一直给我这个错误:

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

这是我的代码:

import SwiftUI

struct ContentView: View {
    //properties
    var co2 = 400
    
    var body: some View {
        Text(airQuality()) //where the error occurs, I'm trying to print the result here
            .font(.custom("Devanagari Sangam MN", size:50))
            .foregroundColor(Color.black)
            .offset(y:300)
    }
    
    //function I'm trying to call
    func airQuality(){
        if co2 > 1000 &&  co2 < 4000{
            print("Bad")
        }
        else if co2 >= 4000 {
            print("Caution")
        }
        else {
            print("Good")
        }
    }
}

我该如何解决?? 太感谢了!

这是一种方法:

由于您没有更改值,因此最好使用 let,不需要 var 或 function。

方式一:

struct ContentView: View {
    
    @State private var co2: Int = 400

    var body: some View {
        
        AirView(co2: co2).padding()
        
        Button("co2 = 400") { co2 = 400 }.padding()
        Button("co2 = 2000") { co2 = 2_000 }.padding()
        Button("co2 = 5000") { co2 = 5_000 }.padding()

    }

}

struct AirView: View {

    let co2: Int
    private let airQuality: String
    
    init(co2: Int) {
        
        self.co2 = co2

        if (co2 > 1_000) && (co2 < 4_000) {
            self.airQuality = "Bad"
        }
        else if (co2 >= 4_000) {
            self.airQuality = "Caution"
        }
        else {
            self.airQuality = "Good"
        }
    }

    var body: some View {
        
        Text("co2 is: " + co2.description + " " + airQuality)

    }

}

方式二:

struct ContentView: View {
    
    @State private var co2: Int = 400

    var body: some View {
        
        Text("co2 is: " + co2.description + " " + co2Function(co2: co2)).padding()
        
        Button("co2 = 400") { co2 = 400 }.padding()
        Button("co2 = 2000") { co2 = 2_000 }.padding()
        Button("co2 = 5000") { co2 = 5_000 }.padding()

    }
    
    
    func co2Function(co2: Int) -> String {

        if (co2 > 1_000) && (co2 < 4_000) {
            return "Bad"
        }
        else if (co2 >= 4_000) {
            return "Caution"
        }
        else {
            return "Good"
        }
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM