Hope
Hope

Reputation: 2326

How do you center Text in ScrollView at SwiftUI

How do you center text here ?

Texts are at the left side of scrollViews.

What is .center for ?

enter image description here

var scrolls =  ["One", "Two", "Three"]
    
    VStack {
        
        Spacer()
        
        ForEach(0..<scrolls.count
                , id: \.self) { index in
            
            ScrollView(.horizontal, showsIndicators: true) {
                
                
                
                Text(" \(scrolls[index])")
                
                    .frame(maxWidth: .infinity,
                           maxHeight: .infinity,
                           alignment: .center)
                
                
                    .background(Color.gray)
                
                
            }
            
            .frame(maxWidth: .infinity,
                   maxHeight:50,
                   alignment:
                    .center)
            
            
            .background(Color.green)
            
        }.frame(alignment: .bottom)
        
        
    }
}

Upvotes: 1

Views: 164

Answers (1)

Asperi
Asperi

Reputation: 257493

You can use GeometryReader and frame(minWidth: for that, like below.

Tested with Xcode 13.2 / iOS 15.2

demo

var body: some View {
    GeometryReader { gr in
        VStack {
            Spacer()
            ForEach(0..<scrolls.count
                      , id: \.self) { index in

                ScrollView(.horizontal, showsIndicators: true) {
                    Text(" \(scrolls[index])")
                        .frame(minWidth: gr.size.width,       // << here !!
                                 maxHeight: .infinity,
                                 alignment: .center)
                        .background(Color.gray)
                }
                .frame(maxWidth: .infinity,
                         maxHeight:50,
                         alignment:
                                .center)
                .background(Color.green)
            }.frame(alignment: .bottom)
        }
    }
}

Upvotes: 2

Related Questions