Search code examples
formsswiftuishapeshstack

SwiftUI Shape Scale Size Such that HStack size does not increase


I'm trying to make the circles fit into the HStack such that the HStack size does not increase. How can I make the circles fit without specifying a fixed frame?

struct ContentView: View {
    
    var body: some View {
        NavigationView {
            Form {
                HStack {
                    Circle()
                        .fill(Color.red)
                        .aspectRatio(1, contentMode: .fit)
                    Text("Hello")
                }
                HStack {
                    Circle()
                        .fill(Color.blue)
                        .aspectRatio(1, contentMode: .fit)
                    Text("Hello")
                }
            }
        }
    }
}

Circles


Solution

  • Here is a sample of various containers to chose from. SwiftUI will do all the layout, automatically handle rotations and device resolutions.

    struct CirclesView: View {
        var body: some View {
            VStack(spacing: 0) {
                Label("Circles", systemImage: "circle").font(.system(size: 24, weight: .black, design: .rounded)).foregroundColor(.pink)
                HStack {
                    Circle()
                        .foregroundColor(.yellow)
                        .frame(width: 32, height: 32)
                    Text("This is a yellow circle")
                    Spacer()
                }
                Circle()
                    .foregroundColor(.orange)
                    .shadow(radius: 10)
                    .frame(width: 75)
                Divider()
                HStack {
                    VStack {
                        Circle().foregroundColor(.blue)
                        Text("Blue").font(.title3)
                        HStack {
                            Circle().foregroundColor(.purple)
                            Text("Purple").font(.caption)
                        }
                    }
                    .padding()
                    .background(Color.yellow)
                    ZStack(alignment: Alignment(horizontal: .center, vertical: .center)) {
                        Circle().foregroundColor(.green)
                        Text("Green").foregroundColor(.primary)
                    }
                }
            }
        }
    }
    

    Circles View