如何在附加到UITextField

时间:2019-06-14 16:06:06

标签: swift uipickerview

我有一个UITextField,它已经附加了一个UIPickerView。

我的UIPickerView有元素

var teeUsed = ["Yellow","Blue","Red","Green"]

我在UITextField中当前的设置是红色

当我输入UITextField时,我的微调器会弹出,并且将Yellow作为首选。我希望RED成为第一选择。如果一切顺利,只要单击另一个字段,它就不会变为黄色。

我尝试过编辑确实开始,着陆,触发了主要操作,但是一切都在填充选择器之前完成,因此如果我尝试选择行,则会崩溃

1 个答案:

答案 0 :(得分:0)

enum AvailableColors: Int {
    case yellow = 0
    case blue = 1
    case red = 2
    case green = 3

    var colorByIndex: UIColor {
        switch (self) {
        case .yellow:
            return .yellow
        case .blue:
            return .blue
        case .red:
            return .red
        case .green:
            return .green
        }
    }
}

class ViewController: UIViewController, UIPickerViewDelegate {
    var picker : UIPickerView?
    var selectedIndex = 0

   override func viewDidLoad() {
       super.viewDidLoad()
       //1.init your picker with data.
       // self.picker = UIPickerView()...
       // self.picker.delegate = self
       //2.select predefined index
       self.picker?.selectRow(self.selectedIndex, inComponent: 0, animated: false)

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
       self.selectedIndex = row
       self.textField.backgroundColor = AvailableColors(rawValue: row)?.colorByIndex
    }
}