具有可选默认参数的 SwiftUI 视图

问题描述 投票:0回答:3

我正在尝试复制我们在 swiftui 中创建带有默认可选参数的函数的方式。

func greet(_ person: String, nicely: Bool = true) {
    if nicely == true {
        print("Hello, \(person)!")
    } else {
        print("Oh no, it's \(person) again...")
    }
}

可以用两种不同的方式调用

greet("Taylor")
greet("Taylor", nicely: false)

是否可以使用相同的逻辑创建 SwiftUI 视图?我想创建一个具有“默认可选”参数的组件,这样我就可以将其称为:

DividerItem(...)
DividerItem(..., isBold: true)

非常感谢!

swift swiftui
3个回答
9
投票

在这里...只需定义视图的变量,给它们默认值,你就可以使用两种不同的初始化来调用它们

struct ContentView: View {
    
    var body : some View {
        DividerItem(text: "Hello World", isBold: true)
        DividerItem(text: "Hello Second World")
    }
}


struct DividerItem : View {
    
    var text : String
    var isBold = false
    
    var body : some View {
        Text(text)
            .fontWeight(self.isBold ? .bold : .medium)
    }
}

4
投票

您可以为您的视图创建自定义初始化程序

struct DividerItem : View {
    var isBold: Bool
    // other properties

    init(/* other params */ isBold: Bool = false) {
        self.isBold = isBold
    }

    var body: some View {
        //....
    }
}

然后使用或不使用布尔参数来调用它

DividerItem(/* other params */)
DividerItem(/* other params */ isBold: true)

0
投票

结构MetricCardView:视图{ var 标题:字符串 变量值:字符串 变量颜色:颜色 变量宽度:CGFloat var iconName:字符串? var iconDescription: 字符串?

var body: some View {
    VStack {

如果让 iconName = iconName,让 iconDecription = iconDecription { 标签(图标名称,系统图像:图标描述) }

        Text(title)
            .font(.headline)
        Text(value)
            .font(.largeTitle)
            .fontWeight(.bold)
    }
    .frame(width: width, height: 100)
    .background(color.opacity(0.2))
    .cornerRadius(10)
}

}

现在您可以调用 MetricCardView() 并将两个 var 标记中的任何一个标记为问号

© www.soinside.com 2019 - 2024. All rights reserved.