如何在 SwiftUI 中设置自定义 PickerView 的宽度?

问题描述

无论我尝试什么,我都无法通过 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,width:pickerView.bounds.width,height: 0))
            
            let imageView = UIImageView(frame: CGRect(x: 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
        }
    }
}

这是结果。

Screen Shot of custom picker view

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

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

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)