Hani Elsayed
Hani Elsayed

Reputation: 11

Using Material MDCCard in SwiftUI with UIViewRepresentable size issue

I'm trying to use Material components MDCCard in SwiftUI and trying to make its size exactly as its subviews but I end up with stretched size to fill any available space in its parent.

How could I make its size wraps its content.

Here is my MaterialCard

struct MaterialCard<Content: View>: UIViewRepresentable {
    let content: () -> Content

    func makeUIView(context: Context) -> MDCCard {
        let card = MDCCard()

        let view = UIHostingController(rootView: content()).view!
        view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        card.addSubview(view)

        return card
    }

    func updateUIView(_ card: MDCCard, context: Context) {
        card.setContentHuggingPriority(.defaultHigh, for: .vertical)
        card.setContentHuggingPriority(.defaultHigh, for: .horizontal)
    }
}

And here is the preview used

struct CCard_Previews: PreviewProvider {
    static var previews: some View {
        VStack {
            MaterialCard(rippled: true) {
                Text("HEllllO")
                    .frame(width: 200, height: 200)
                    .background(Color.red.opacity(0.5))
            }
            .background(Color.gray)
            .environment(\.colorScheme, .light)

            MaterialCard(rippled: true) {
                Text("HEllllO")
                    .frame(width: 200, height: 200)
                    .background(Color.red.opacity(0.5))
            }
            .background(Color.black)
            .environment(\.colorScheme, .dark)
        }
    }
}

And the result is

Result

Upvotes: 1

Views: 437

Answers (0)

Related Questions