aaronium112
aaronium112

Reputation: 3088

How to size a Image to 1/3 of the width of the row in SwiftUI?

Here's what i've got. I've tried putting the GeometryReader at different scopes but this is the best result so far.

You can the image is the correct width and height but the cell in the List is not tall enough.

struct AvtrCell: View
{
    var avtr: Avatar
    var body: some View {
        GeometryReader { g in
            NavigationLink(destination: AvtrForm(avtr: self.avtr)){
                HStack() {
                    Image(self.avtr.img)
                        .resizable()
                        .aspectRatio(1, contentMode: .fill)
                        .cornerRadius(9)
                        .frame(width: g.size.width / 3)

                    VStack(alignment: .leading) {
                        Text("\(self.avtr.firstName()) \(self.avtr.lastName())").font(.headline)
                        Text("44hr Weekly Fasts")
                        Text("2000cal, prtn: 10g, fat: 10g, crb: 4g")
                        Text("Chest: 40, Waist: 32, Hips: 35")
                        Text("175ibs, 93% lean")
                        Text("pH: 9")
                    }
                    .font(.subheadline)
                    .lineLimit(1)
                }
            }
        }
    }
}

demo

Please advise.

Upvotes: 0

Views: 1014

Answers (1)

Asperi
Asperi

Reputation: 257711

You can't avoid ambiguity working with GeometryReader being already inside row. So the solution is to pass needed parameter from outside.

Tested with replicated code on Xcode 11.4 / iOS 13.4

demo

// Just tested replicated view

struct TestImageInRow: View {
    var body: some View {
        GeometryReader { g in
            NavigationView {
                List {
                    AvtrCell(imageWidth: g.size.width / 3)
                    AvtrCell(imageWidth: g.size.width / 3)
                    AvtrCell(imageWidth: g.size.width / 3)
                    AvtrCell(imageWidth: g.size.width / 3)
                }
            }
        }
    }
}

// Updated original cell
struct AvtrCell: View
{
    var imageWidth: CGFloat    // << here
    var avtr: Avatar
    var body: some View {
        NavigationLink(destination: AvtrForm(avtr: self.avtr)){
            HStack() {
                Image(self.avtr.img)
                    .resizable()
                    .aspectRatio(1, contentMode: .fill)
                    .cornerRadius(9)
                    .frame(width: imageWidth)   // << here 

    // ... other code

Upvotes: 1

Related Questions