swiftui

Shrinking Picker to fit content and no larger


I am developing a MacOS app using SwiftUI and would like a Picker to shrink to only show its label and content, and a Spacer to take up the rest of the view, but I'm not sure what the correct way to do this. The code looks something like this:

HStack{
    Text("hello")
    Text("more text")
    Spacer()
    Picker(selection: self.$stuff, label: Text("some stuff:")) {
        ForEach(0 ..< self.getStuff().count) {
            Text(self.getStuff()[$0])
        }
    }
}

and the Picker is expanded to take up as much room as possible. I would prefer that the picker take up the minimum amount of space and the Spacer to take up the remaining space.

Edit: photo:

enter image description here


Solution

  • You can use .scaledToFit to fit it to content as below

    swiftui macOS picker/popup

        Picker(selection: self.$stuff, label: Text("some stuff:")) {
            ForEach(0 ..< self.getStuff().count) {
                Text(self.getStuff()[$0])
            }
        }
        .scaledToFit()
    //  .frame(width: 160) // < alternate approach - give explicit desired width