user3577166
user3577166

Reputation: 602

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

Upvotes: 10

Views: 3227

Answers (2)

Anton
Anton

Reputation: 1785

.scaledToFit() does not work for me, but .fixedSize() does.

Picker(selection: self.$stuff, label: Text("some stuff:")) {
    ForEach(0 ..< self.getStuff().count) {
        Text(self.getStuff()[$0])
    }
}
.fixedSize(horizontal: true, vertical: true)

Upvotes: 2

Asperi
Asperi

Reputation: 258247

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

Upvotes: 10

Related Questions