3

I'm a beginner in swift and trying to learn UIPickerView which has done button to close after the selection from the picker view. I have following code to add the tool bar and the done button to the picker as a toolbar in subview. It shows up as a blank black toolbar (attached screenshot) enter image description here

let toolBar = UIToolbar()
toolBar.barStyle = .black
toolBar.sizeToFit()
let doneBtn = UIBarButtonItem.init(title: "Done", style: .plain, target: self, action: #selector(self.closePicker))
toolBar.items = [doneBtn]
toolBar.isUserInteractionEnabled = true
picker.addSubview(toolBar) 

Picker is the outlet for UIPickerView in my controller. What am I doing wrong? I referred to other questions but they dont seem to solve my problem. Any suggestions?

Revanth Kausikan
  • 673
  • 1
  • 9
  • 21
pritesh
  • 533
  • 4
  • 15

2 Answers2

0

You are wrong at this line:

picker.addSubview(toolBar)

Picker is not supposed to have any subviews - it's a comprehensive view by itself and there is no area in it to accommodate anything in addition.

Instead you need to add both the picker and the toolbar on the same view and align them next to each other

let toolBar = UIToolbar()
...configure your toolbar here...
guard let superview = picker.superview else { return }
superview.addSubview(toolBar)
toolBar.translateAutoresizingMaskIntoConstraints = false
NSLayoutConstraints.activate([
    toolBar.topAnchor.constraint(equalTo: superview.topAnchor),
    toolBar.leftAnchor.constraint(equalTo: superview.leftAnchor),
    toolBar.rightAnchor.constraint(equalTo: superview.rightAnchor),
    toolBar.bottomAnchor.constraint(equalTo: picker.topAnchor)
])
The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49
-1

You should not add toolBar as subView of picker.

You should set the toolBar as inputAccessoryView of textField.

As I searched for this problem I got that the common way (also easiest way) to achieve what you want is Using dummy textField.

It means create a textField at the exact frame of button and hide it, when user touches the button make the textField firstResponder.

@IBAction func pickerButtonClicked(_ sender: Any) {
    self.pickerViewTextField.becomeFirstResponder
}
Arash Etemad
  • 1,827
  • 1
  • 13
  • 29
  • Im showing it on click of button and it says its a read-only property. Please help me with the code. – pritesh Mar 18 '19 at 13:11