1

无论我尝试什么,我都无法使用 UIViewRepresentable 控制集成到 Swift UI 中的自定义选择器视图的宽度。这是内容视图:

struct ContentView: View {
    @State private var pickerData:[[String]] =
        [
            ["silhouette_1" , "silhouette_2" , "silhouette_3" ],
            ["silhouette_2" , "silhouette_3" , "silhouette_1" ],
            ["silhouette_3" , "silhouette_1" , "silhouette_2" ]
        ]
    
       var body: some View {
        VStack{
            SilhouettePickerView(pickerData: $pickerData)
            }
       }
   }

这是 SilhouettePickerView:

struct SilhouettePickerView: UIViewRepresentable {
    @Binding var pickerData : [[String]]
    func makeCoordinator() -> SilhouettePickerView.Coordinator {
        return SilhouettePickerView.Coordinator(self)
    }

    func makeUIView(context: UIViewRepresentableContext<SilhouettePickerView>) -> UIPickerView {
        let picker = UIPickerView(frame: .zero)
        //let picker = UIPickerView(frame: CGRect(x: 0, y: 0, width: ????, height: ?????))

        picker.dataSource = context.coordinator
        picker.delegate = context.coordinator
        return picker
    }
    func updateUIView(_ view: UIPickerView, context: UIViewRepresentableContext<SilhouettePickerView>) {
    }

    class Coordinator: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {
        var parent: SilhouettePickerView
        init(_ pickerView: SilhouettePickerView) {
            self.parent = pickerView
        }
   
        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return parent.pickerData.count
        }
        
        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return parent.pickerData[component].count
        }
        
        func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
            //return UIScreen.main.bounds.width/3
            pickerView.bounds.width/3 - 8
        }

        func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
            return 126
        }
      
        func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

            let view = UIView(frame: CGRect(x: 0, y: 0, width:pickerView.bounds.width, height: 0))
            
            let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 90, height: 126))
            for _ in 0..<self.parent.pickerData.count {
                imageView.image = UIImage(named: self.parent.pickerData[component][row])
            }
            view.addSubview(imageView)
            return view
        }
    }
}

这就是结果。自定义选择器视图的屏幕截图

我希望它填满更多的屏幕。另外,我希望组件行居中;你会注意到右边缘的灰色。(无论如何要摆脱它?)我已经在makeUIView中设置了帧大小:

let picker = UIPickerView(frame: CGRect(x: 0, y: 0, width: 400, height: 200))

但没有任何改变。有什么建议么?谢谢!

4

0 回答 0