【问题标题】:How do you implement functions in SwiftUI?如何在 SwiftUI 中实现函数?
【发布时间】:2020-04-20 12:40:22
【问题描述】:

我有一个包含一系列图像和文本框的用户界面,我想知道为什么我不能为每个图像和文本框定义一个函数,并为每个输入一个变量。

这是我要定义的文本函数:

   func textBox(textIn: String) {
    Text("\(textIn)")
    .fontWeight(.bold)
    .foregroundColor(Color.white)
    .background(Color.blue)
    .offset(y: 65)
}

当我想调用它告诉我的函数时

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

var body: some View {
    VStack{
    NavigationView {
        ScrollView {

textBox(textIn: "Test!")

我才编程几个月,而且我在 Swift 中工作不到一周,所以如果这是一个基本问题,我很抱歉。

提前致谢

里程

【问题讨论】:

    标签: swift xcode swiftui


    【解决方案1】:

    您需要做的是从您的函数中返回一个视图,如下所示:

    import SwiftUI
    
    struct ContentView: View {
    
    var body: some View {
        VStack{
            NavigationView {
                ScrollView {
                    textBox(textIn: "Test!")
                }
            }
        }
    }
    
    func textBox(textIn: String) -> AnyView {
        AnyView(Text("\(textIn)")
            .fontWeight(.bold)
            .foregroundColor(Color.white)
            .background(Color.blue)
            .offset(y: 65)
        )
    }
    }
    

    它甚至可以用这个:

    func textBox(textIn: String) -> some View {
        Text("\(textIn)")
            .fontWeight(.bold)
            .foregroundColor(Color.white)
            .background(Color.blue)
            .offset(y: 65)
    }
    

    【讨论】:

    • 谢谢!使用某些视图而不是指定视图有什么缺点吗?
    猜你喜欢
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 2020-10-09
    • 2021-09-23
    • 1970-01-01
    • 2012-01-07
    • 2015-11-13
    相关资源
    最近更新 更多