How to create combobox in swift?

1

I want to create a comboBox to list all the courses that my app offers, but I did not find the corresponding component, alias I found a similar one and implemented PickerView, but I would like to reproduce the default behavior of a:

<select>
  <option>Red</option>
  <option>Blue</option>
  <option>Yellow</option>
</select>

And in my case it looks like this:

How could I reproduce the same behavior?

    
asked by anonymous 30.06.2016 / 17:04

1 answer

5

PickerView is the native component for this type of action in iOS

You can use some solutions like Collapse TableView , or an adaptation of UITextField + PickerView .

An interesting solution I found uses UITextField + Popover :


Usage example:

// Adicione um textfield no Storyboard e mude a classe dele para SRKComboBox.
@IBOutlet weak var myComboBox:SRKComboBox!

// Array qualquer
let arrayForComboBox = ["Sagar", "Sagar R. Kothari", "Kothari", "sag333ar", "sag333ar.github.io", "samurai", "jack", "cartoon", "network"]


//MARK:- UITextFieldDelegate

func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
  if let txt = textField as? SRKComboBox {
    txt.delegateForComboBox = self
    txt.showOptions()
    return false
  }
  if let txt = textField as? SRKDateTimeBox {
    txt.delegateForDateTimeBox = self
    txt.showOptions()
    return false
  }
  return true
}

//MARK:- SRKComboBoxDelegate
//Adicione os delegates

func comboBox(textField:SRKComboBox, didSelectRow row:Int) {
  if textField == self.myComboBox {
    self.myComboBox.text = self.arrayForComboBox[row]
  }
}

func comboBoxNumberOfRows(textField:SRKComboBox) -> Int {
  if textField == self.myComboBox {
    return self.arrayForComboBox.count
  } else {
    return 0
  }
}

func comboBox(textField:SRKComboBox, textForRow row:Int) -> String {
  if textField == self.myComboBox {
    return self.arrayForComboBox[row]
  } else {
    return ""
  }
}

func comboBoxPresentingViewController(textField:SRKComboBox) -> UIViewController {
  return self
}

func comboBoxRectFromWhereToPresent(textField:SRKComboBox) -> CGRect {
  return textField.frame
}

func comboBoxFromBarButton(textField:SRKComboBox) -> UIBarButtonItem? {
  return nil
}

func comboBoxTintColor(textField:SRKComboBox) -> UIColor {
  return UIColor.blackColor()
}

func comboBoxToolbarColor(textField:SRKComboBox) -> UIColor {
  return UIColor.whiteColor()
}

func comboBoxDidTappedCancel(textField:SRKComboBox) {
  textField.text = ""
}

func comboBoxDidTappedDone(textField:SRKComboBox) {
  print("Let's do some action here")
}

Expected result:

    
30.06.2016 / 18:59