Search code examples
iosswiftswiftui

How to give inside padding to a Text in SwiftUI


struct MostViewedViewItem: View {
    let moviePic: String = "image_placeholder"
    let movieName: String = "Movie Name Loading..."
    
    var body: some View {
        Button {
            // TODO: add a navigation link to the movie
        } label: {
            ZStack(alignment: .bottom) {
                Image(moviePic)
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: 170, height: 100)
                    .clipShape(RoundedRectangle(cornerRadius: 3))
                    .overlay(
                        Text(movieName)
                            .scaledToFill()
                            .frame(height: 30)
                            .foregroundColor(.white)
                            .background (
                                Rectangle()
                                    .fill(Color("lighter_bg"))
                                    .opacity(0.4)
                            ),
                        alignment: .bottom
                    )
            }
        }
    }
}

enter image description here

I'm trying to add padding inside the background, so I want the background to be fill the whole horizontal spaace, but I want the text to have some padding, how to do that?


Solution

  • You should add padding before the .background. Also, you may want to use frame instead of scaledToFill like this:

    Text(movieName)
        .frame(maxWidth: .infinity)
        .foregroundColor(.white)
        .padding()
        .background(Color("lighter_bg").opacity(0.4))
    

    Here is another answer for better demonstration of applying paddings