How do I get my UIView to correctly size for its content in SwiftUI?

十年热恋 提交于 2020-05-17 02:57:13

问题


I want to use the awesome MultiSegmentPicker written by Yonat Sharon in my SwiftUI View.

https://github.com/yonat/MultiSelectSegmentedControl

However, I don't fully understand the interaction between the UIViewRepresentable View and my SwiftUI View. How do I get the host view controller to shrink its height down to the size of the segmented control?

Here's the debugger view of the demo page - notice the blue area around the top bar:

The demo code doesn't give a lot of insight into the issue, it's just a call to the UIViewRepresentable view. I've simplified it to just one example here:

   struct MultiSegmentPickerX: View {

    @State private var selectedSegmentIndexes: IndexSet = []

    var body: some View {
        VStack(alignment: .center) {
            Spacer()
            MultiSegmentPicker(
                selectedSegmentIndexes: $selectedSegmentIndexes,
                items: ["First", "Second", "Third", "Done"]
            )
        }
    }
}

Notice I have a VStack with a Spacer() before the control.

The desired behavior for this example would be that the bar with "First", "Second", etc. would be snug against the bottom of the screen. Instead the Host Controller holds onto all that space...

Do I need to use Geometry reader to solve this issue and shrink the height down. Or do I have to adjust something in the UIViewRepresentable View?

Any insights into bridging UIKit and SwiftUI are always appreciated... Is this an easy fix anyone?

These did not solve my issue: UIViewRepresentable content not updating

How do I make SwiftUI UIViewRepresentable view hug its content?

How do I size a UITextView to its content?


回答1:


Cannot test it now, just by thoughts, try with fixed size as below

MultiSegmentPicker(
    selectedSegmentIndexes: $selectedSegmentIndexes,
    items: ["First", "Second", "Third", "Done"]
).fixedSize()       // << here !!


来源:https://stackoverflow.com/questions/61254931/how-do-i-get-my-uiview-to-correctly-size-for-its-content-in-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!