Deva raj
Deva raj

Reputation: 11

Add view to contentView using function swiftUI not working

I had a function that will have a Text().I called the function inside body but not shows.

struct ContentView: View {
var body: some View {
    Text("").onAppear(perform: data)   
}

func data() {
    Text("sweet")
}

}

Upvotes: 0

Views: 658

Answers (1)

not clear what you trying to do, but you cannot show Text("sweet") using your approach. Try these:

@State var txtData = ""
var body: some View {
        Text(txtData).onAppear(perform: doData)
}
func doData() {
    self.txtData = "sweet"
}

or:

@State var showText = false
var body: some View {
    Group {
        Text("xxxx").onAppear(perform: doShowText)
        if showText {
            Text("sweet")
        }
    }
}
func doShowText() {
    self.showText = true
}

or a variation of this:

@State var myStuff = [AnyView]()
@State var txtfield = ""
var body: some View {
    List {
        ForEach(self.myStuff.indices, id: \.self) { i in
            self.myStuff[i]
        }
    }.onAppear(perform: loadData)
}
func loadData() {
    self.myStuff.append(AnyView(Text("text 1")))
    self.myStuff.append(AnyView(TextField("textfield 1", text: $txtfield)))
}

Upvotes: 0

Related Questions