UIPickerView作为UITextView swift的inputView

时间:2018-05-16 06:14:47

标签: ios swift uitextview uipickerview

我使用UIPickerView作为UITextView的inputView。 selectRow:功能无法正确选择其他时间

这是代码

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
}

print语句打印正确的行,但selectRow:函数选择前一个选择的值,错误是什么?即使状态栏在每个交替时间都变黑,仅用于此UITextView交互。

1 个答案:

答案 0 :(得分:2)

每次都不要创建UIPickerView

创建全局对象

var codePicker = UIPickerView()

和viewDidLoad方法

添加以下代码

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

解决状态栏问题

IQKeyboardManager.sharedManager().canAdjustAdditionalSafeAreaInsets = true

希望它有用