user1366265
user1366265

Reputation: 1426

Fixing overlapping views in SwiftUI

I am trying to build a screen similar to the following. enter image description here

But there are few things that are wrong with this screen:

  1. The image and the text below it are not exactly the same width. The image is slightly wider.
  2. The image and its associated text overlap the text above it.
  3. The text underneath the image is truncated.

I've been on this for two days with no luck! Can someone provide feedback on how I can achieve this? Below is what I have in terms of code.

struct ImageTitleTileView: View {
    var body: some View {
         GeometryReader { geometry in
            VStack(spacing: 0) {
                Image("image")
                    .resizable()
                    .frame(width: geometry.size.width)
                    .aspectRatio(1, contentMode: .fill)

                Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.")
                    .padding()
                    .background(Color.white)
            }
            .edgesIgnoringSafeArea(.all)
        }.aspectRatio(contentMode: .fit)
    }
}

struct MainItemView: View {
    var body: some View {
        ZStack {
            Color(.whiteSmoke)
            VStack(spacing: 10) {
                Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.")

                ImageTitleTileView()
            }.padding(16)
        }
    }
}

Upvotes: 0

Views: 4565

Answers (2)

What its happening is that your image is showing the image part outside your frame.

You need to set clipped() property to the image to hide the image parts outside your frame.

Image("image")
      .resizable() // allow image to be resizable
      .scaledToFill() // scale your image as you need it to fill or to fit
      .frame(height: 200, alignment: .center) // set image frame size
      .aspectRatio(contentMode: .fill) // image aspect ratio
      .clipped() // hide image outside the frame parts (CSS: overflow: hidden)

Upvotes: 2

E.Coms
E.Coms

Reputation: 11531

Just change some parameters . You can get this work. One is the image ratio from 1.0 to 0.9; The other is moving the frame from image to Stack; The last is removing the padding from the 'text'

struct ImageTitleTileView: View {
var body: some View {
     GeometryReader { geometry in
        VStack(spacing: 0) {
            Image("image")
                .resizable()
                .aspectRatio(0.90, contentMode: .fill)
            Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.")
                .background(Color.white)
        }.frame(width: geometry.size.width / 1.5)
        .edgesIgnoringSafeArea(.all)
    }.aspectRatio(contentMode: .fit)
}
}

Upvotes: 1

Related Questions