如何在SwiftUI中单击按钮添加UI组件?

时间:2019-12-16 03:45:36

标签: ios swift swiftui

enter image description here我想在单击任意按钮时在屏幕上再添加一个Text或TextField(UI组件)。

我的代码:

Button(action: { 

        Text("Adding Text after button clicked") 
        .font(.largeTitle) .fontWeight(.light) 
        .foregroundColor(Color.green) 

}) { Text("Add Text") }

1 个答案:

答案 0 :(得分:2)

您可以基于Button的点击添加随机用户界面:

struct ContentView: View {
    @State var isAddUI: Bool = false

    var body: some View {
        VStack(spacing: 20) {
            Text("Hello..").font(.largeTitle).fontWeight(.bold)

            if isAddUI {
                Text("Adding Text after button clicked")
                .font(.largeTitle)
                .fontWeight(.regular)
            }

            Button(action: {
                self.isAddUI = true
            }) { Text("Add Text") }
        }
    }
}