Home > other >  How to fill SwiftUI's VStack from bottom to top with items
How to fill SwiftUI's VStack from bottom to top with items

Time:06-09

I have been searching but could not find a way.

I would like to fill VStack view from bottom to top. When a Text view added as a child to VStack for example it is places at the top. I wanted to add it to the bottom of screen and second one on top of the first one.

@State var items: [Int] = [0]

var body: some View {
    HStack {
        
        Button(action: {
            
            items.append( items.count   1)
            
        }){
            Text("Add")
        }
        
        
        
        ScrollView() {
            ForEach(0..<items.count, id: \.self) { index in
                VStack(spacing:5) {
                    Text(String(items[index]))
                }
            }
        }
    }
}

What you get on top of screen;

1

2

What I want at the bottom of screen;

2

1

CodePudding user response:

You can achieve it by applying rotationEffect to your ScrollView and its inner content.

@State var items: [Int] = [0]

var body: some View {
    
    HStack {
        
        Button(action: {
            //Insert Items at 0 position to add content from bottom to top side
            items.insert(items.count, at: 0)
        }){
            Text("Add")
        }
        
        
        ScrollView(showsIndicators: false) {

                ForEach(0..<items.count, id: \.self) { index in

                    Text(String(items[index])).padding(.vertical,5)

                }.rotationEffect(Angle(degrees: 180)) //After rotating scrollview, now rotate your inner content to upright position.

        }.rotationEffect(Angle(degrees: -180)) //Rotate scrollview to bottom side
    }
}

CodePudding user response:

How's this?

ScrollView {
  VStack(spacing: 5) {
    Spacer()
    ForEach(items.map(String.init).reversed(), id: \.self) { item in
      Text(item)
    }
  }
}
  • Related