简体   繁体   中英

displays values of array in ForEach Swift UI

I am using SwiftUI and I want to simply display array values in a Text form.

Here is my code:

    ForEach(0..<returnCont().count) {
       Text("\(returnCont()[$0]),")
    }

I also tried this:

    ForEach(returnCont().indices) {
        Text("\(return()[index]),")
    }

Where returnCont() is a function returning an array.

The array displays elements that are initialised, but when the array is empty and then appended through user inputs, it only displays values in the terminal, but not in the Text form on the View.

No error is displayed either, just empty text.

Try something like below-:

import SwiftUI


class Model:ObservableObject{
    var dataArray = ["1","2","3"]
    func returnCont() -> Int{
        return dataArray.count
    }
}
struct myView:View{
    @ObservedObject var model = Model()
    var body: some View{
        ForEach(0..<model.returnCont()) { index in
            Text("\(model.dataArray[index]),")
           }
    }
}

I don't know how your model class looks like, so this is just a demo to give you correct idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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