我正在尝试使用UIViewRepresentable
将此picker view中的GitHub repo合并到我的SwiftUI项目中。
我创建了一个测试项目来说明我遇到的问题。以下是构建项目所需的代码(不包括PickerView
,我是从here中提取的)。
struct Fruit {
let name: String
let isInStock: Bool
static let apple = Fruit(name: "apple", isInStock: true)
static let orange = Fruit(name: "orange", isInStock: true)
static let banana = Fruit(name: "banana", isInStock: true)
static let raspberry = Fruit(name: "raspberry", isInStock: false)
static let blueberry = Fruit(name: "blueberry", isInStock: false)
static let lemon = Fruit(name: "lemon", isInStock: true)
static let lime = Fruit(name: "lime", isInStock: false)
}
struct ContentView: View {
@State private var fruits: [Fruit] = [.apple, .orange, .banana, .raspberry, .blueberry, .lemon, .lime]
@State private var selectedFruit: Fruit = .apple
var body: some View {
FruitPicker(fruits: self.$fruits, selectedFruit: self.$selectedFruit)
}
}
struct FruitPicker: UIViewRepresentable {
@Binding var fruits: [Fruit]
@Binding var selectedFruit: Fruit
class Coordinator: NSObject, PickerViewDelegate, PickerViewDataSource {
@Binding var fruits: [Fruit]
@Binding var selectedFruit: Fruit
init(fruits: Binding<[Fruit]>, selectedFruit: Binding<Fruit>) {
self._fruits = fruits
self._selectedFruit = selectedFruit
}
func pickerViewNumberOfRows(_ pickerView: PickerView) -> Int {
return self.fruits.count
}
func pickerViewHeightForRows(_ pickerView: PickerView) -> CGFloat {
return 50
}
func pickerView(_ pickerView: PickerView, titleForRow row: Int) -> String {
return self.fruits[row].name
}
func pickerView(_ pickerView: PickerView, didSelectRow row: Int) {
self.selectedFruit = self.fruits[row]
}
}
func makeCoordinator() -> FruitPicker.Coordinator {
return Coordinator(fruits: self.$fruits, selectedFruit: self.$selectedFruit)
}
func makeUIView(context: UIViewRepresentableContext<FruitPicker>) -> PickerView {
let pickerView = PickerView()
pickerView.delegate = context.coordinator
pickerView.dataSource = context.coordinator
return pickerView
}
func updateUIView(_ pickerView: PickerView, context: UIViewRepresentableContext<FruitPicker>) {
}
}
PickerView
使用UITableView
模仿UIPickerView
的功能,但外观平坦。
运行项目时,UITableViewDelegate
和UITableViewDataSource
的{{1}}中的PickerView.swift
和heightForRowAtIndexPath
方法都被调用,但是numberOfRowsInSection
不是。
我首先尝试从“调试”选项卡中选择“调试视图层次结构”,但是每次执行Xcode都会崩溃。因此,我随后设置了背景颜色,以查看选择器视图是否完全出现在屏幕上,而实际上没有,因此我在cellForRowAtIndexPath
和makeUIView
内放置断点以检查updateUIView
帧。在两种情况下,它都返回零。我尝试在PickerView
中为选择器视图设置框架,但没有任何变化-makeUIView
根本不会被调用。
有人对我要去哪里错或者到底是什么导致cellForRowAtIndexPath
永远不会被叫有任何想法吗?