SwiftUI:设置选择器行高

SwiftUI: Setting Picker line height

对于大字体,Picker 中的行是重叠的。如何更改 Picker's 行高? (提示:.lineSpacing 修饰符不会这样做。)

另请参阅

这个问题与 Ejaaz 的问题类似,但他的问题目前还没有答案。

问题

代码

以下可运行代码产生上述结果。我真的不想要不同大小的线条,我只希望大字体适合。我试过插入 Spacers,在这里和那里添加 .frame 修饰符,.lineSpacingpadding() ...也许只是没有找到正确的组合?

struct ContentView: View {
    @State private var selected = 0

    var body: some View {
        Picker(selection: self.$selected, label: Text("Letters")) {
            Text("A").font(.system(size: 30))
            Text("B").font(.system(size: 40))
            Text("C").font(.system(size: 50))
            Text("D").font(.system(size: 60))
            Text("E").font(.system(size: 70))
            Text("F").font(.system(size: 80))
        }
    }
}

您必须将 UIPickerView 包装在 UIVieweRepresentable 中,然后使用

 func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat 

更改行高。

示例:(它只是展示了如何更改行高,您仍然需要为您的内容扩展它...)

struct PickerView: UIViewRepresentable {
    var data: [[String]]
    @Binding var selections: Int

    //makeCoordinator()
    func makeCoordinator() -> PickerView.Coordinator {
        Coordinator(self)
    }

    //makeUIView(context:)
    func makeUIView(context: UIViewRepresentableContext<PickerView>) -> UIPickerView {
        let picker = UIPickerView(frame: .zero)

        picker.dataSource = context.coordinator
        picker.delegate = context.coordinator

        return picker
    }

    //updateUIView(_:context:)
    func updateUIView(_ view: UIPickerView, context: UIViewRepresentableContext<PickerView>) {
//        for i in 0...(self.selections.count - 1) {
//            view.selectRow(self.selections[i], inComponent: i, animated: false)
//        }
    }

    class Coordinator: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {
        var parent: PickerView

        //init(_:)
        init(_ pickerView: PickerView) {
            self.parent = pickerView
        }

        func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
            return 80
        }

        //numberOfComponents(in:)
        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return self.parent.data.count
        }

        //pickerView(_:numberOfRowsInComponent:)
        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return self.parent.data[component].count
        }

        //pickerView(_:titleForRow:forComponent:)
        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return self.parent.data[component][row]
        }

        //pickerView(_:didSelectRow:inComponent:)
        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
     //       self.parent.selections[component] = row
        }
    }
}