Search code examples
iosswiftuitextviewuipickerview

UIPickerView as inputView for UITextView swift


I have used UIPickerView as inputView for UITextView. The selectRow: function doesn't select properly for alternate time

Here is the code

func textViewDidBeginEditing(_ textView: UITextView) {
    let inputView = UIView(frame: CGRect(x: 0,y: 0, width: self.view.frame.width, height: 240))
    let codePicker = UIPickerView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 240))
    codePicker.tag = 2

    if codePicker.dataSource == nil {
        codePicker.dataSource = self
    }
    if codePicker.delegate == nil {
        codePicker.delegate = self
    }

    codePicker.showsSelectionIndicator = true
    print("selectedBankRow: \(selectedRow)")
    codePicker.selectRow(selectedRow, inComponent: 0, animated: true)
    inputView.addSubview(codePicker)
    textView.inputView = inputView
    return
}

The print statement print correct row but the selectRow: function selects the previous to the previous value which was selected, what could be the error? Even the status bar goes black each alternate time only for this UITextView interaction.


Solution

  • Don't create UIPickerView every time

    Create Global Object

    var codePicker = UIPickerView()
    

    and in viewDidLoad Method

    add following code

    let inputView = UIView(frame: CGRect(x: 0,y: 0, width: self.view.frame.width, height: 240))
    codePicker = UIPickerView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 240))
    codePicker.tag = 2
    codePicker.dataSource = self
    codePicker.delegate = self
    
    codePicker.showsSelectionIndicator = true
    print("selectedBankRow: \(selectedRow)")
    codePicker.selectRow(selectedRow, inComponent: 0, animated: true)
    inputView.addSubview(codePicker)
    textView.inputView = inputView
    

    as you solved Status bar issue with

    IQKeyboardManager.sharedManager().canAdjustAdditionalSafeAreaInsets = true
    

    Hope it is helpful