简体   繁体   中英

SwiftUI: How to set custom view size dynamically

I use SwiftUI. I need a custom view. The custom view width should be equal to the superview width. The custom view contains two image views, aligning left and right respectively. Each image view has the same width and height (aspect ratio = 1). Two image views have 10 points space. I will display different size images in the image view (scale aspect fill).

在此处输入图片说明

If I use GeometryReader , I can set the image view frame dynamically, but how to set the GeometryReader frame dynamically? If I use HStack without GeometryReader , the image views frames are variable. How to do this in SwiftUI?

Perhaps some variant of the following:

struct CustomView: View {
    var body: some View {
        HStack(spacing: 10) {
            Image(systemName: "heart.fill")
                .resizable()
                .aspectRatio(1, contentMode: .fit)

            Image(systemName: "heart.fill")
                .resizable()
                .aspectRatio(1, contentMode: .fit)
        }.frame(maxWidth: .infinity)
    }
}

Both images maintain a 1:1 aspect ratio, with 10 points of spacing between them, but are allowed to grow horizontally using the .frame modifier.

Replace Image(systemName: "heart.fill") with a desired image source as needed.

If your source image asset does not have a 1:1 aspect ratio, set the contentMode to .fill , and constrain the frame height of either the HStack or the CustomView inside its parent using .frame(height: ..) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM