Home > Software design >  SwiftUI picker scale to fit selection
SwiftUI picker scale to fit selection

Time:06-02

I have a picker like the following that has a frame width of 150. I need the text to fit inside the picker, but the lineLimit(), scaledToFit() and scaledToFill() do not do anything on the picker object.

@State var Status: String = ""

Picker(selection: $Status, label:
        Text("Status")) {
            Text("yyyyyyyyyyyyyyyyyyyyyyyyyyyyy").tag(0)
                .lineLimit(2).scaledToFit().scaledToFill()
            Text("zzzzzzzzzzzzzzzzzzzzzzzzzzzzz").tag(1)
                .lineLimit(2).scaledToFit().scaledToFill()
        }.frame(maxWidth: 150, minHeight: 50, maxHeight: 50, alignment:.center)
         .background(Color.gray)
         .lineLimit(2)
         .scaledToFit()

What is the correct way to scale and fit selected text inside the picker?

enter image description here

Thank you for any help!!

CodePudding user response:

I was unable to figure out how to do it with the picker object in SwiftUI, so I ended up creating a custom picker view that resizes the selected value in the frame.

struct PickerView: View{
    @State var picking: Bool = false
    @State var Status: String = ""
    @State var ValueList = ["yyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
                             "zzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
                             "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"]
    var body: some View{
        CustomPicker(picking: $picking, Status: $Status, ValueList: $ValueList).onTapGesture{
            picking = true
        }
    }
}

struct CustomPicker: View{
    @Binding var picking: Bool
    @Binding var Status: String
    @Binding var ValueList: [String]
    var body: some View{
        HStack{
            HStack{
                if Status == "" {
                    Text("Pick Value")
                } else {
                    Text(Status).lineLimit(2)
                }
            }.frame(maxWidth: 150, minHeight: 50, maxHeight: 50, alignment:.center)
            .background(Color.gray)
        }.sheet(isPresented: $picking, content: {
            ForEach(ValueList, id: \.self){ item in
                Text(item).onTapGesture {
                    Status = item
                    picking = false
                }.foregroundColor(Color.blue).padding().border(Color.gray)
            }
        })
    }
}

You tap to pick a value

enter image description here

You can then select a value

enter image description here

And it displays correctly within the box

enter image description here

CodePudding user response:

Try rather using scaleToFill with a lineLimit of 1.

Check out Apple's Documentation
Another good StackOverflow answer

Example:

Text("yyyyyyyyyyyyyyyyyyyyyyyyyyyyy").tag(0).lineLimit(1).scaledToFill()
  • Related