所以我点击页面上有一个按钮我打开了一个选择器视图。我用几个月填充了选择器视图。我添加了一个工具栏,但每当我尝试选择它时,只需将选择器视图滚动到顶部。
monthPicker = UIPickerView(frame: CGRect(x: 0, y: self.view.frame.size.height- monthPicker.frame.size.height, width: self.view.frame.size.width, height: monthPicker.frame.size.height))
monthPicker.delegate = self
monthPicker.dataSource = self
monthpickerData = ["January","February","March","April","May","June","July","August","September","October","November","December"]
monthPicker.backgroundColor = UIColor.white
//
let btnDone = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.monthdoneButtonAction))
let barAccessory = UIToolbar(frame: CGRect(x: 0, y: 0, width: monthPicker.frame.size.width, height: 44))
barAccessory.barStyle = .default
barAccessory.isTranslucent = false
barAccessory.items = [flexiblespace,btnDone]
monthPicker.addSubview(barAccessory)
答案 0 :(得分:4)
似乎UIPickerView不允许其子级接收触摸事件。如果您与UITextField一起显示它,您可以使用它的inputView和inputAccessoryView来实现相同的功能。或者,您可以创建一个顶级容器UIView来保存工具栏和选择器视图,如下所示:
let picker = UIView(frame: CGRect(x: 0, y: view.frame.height - 260, width: view.frame.width, height: 260))
// Toolbar
let btnDone = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.monthdoneButtonAction))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(self.cancelClick))
let barAccessory = UIToolbar(frame: CGRect(x: 0, y: 0, width: picker.frame.width, height: 44))
barAccessory.barStyle = .default
barAccessory.isTranslucent = false
barAccessory.items = [cancelButton, spaceButton, btnDone]
picker.addSubview(barAccessory)
// Month UIPIckerView
monthPicker = UIPickerView(frame: CGRect(x: 0, y: barAccessory.frame.height, width: view.frame.width, height: picker.frame.height-barAccessory.frame.height))
monthPicker.delegate = self
monthPicker.dataSource = self
monthpickerData = ["January","February","March","April","May","June","July","August","September","October","November","December"]
monthPicker.backgroundColor = UIColor.white
picker.addSubview(monthPicker)