How to create combobox in Swift?

Asked

Viewed 1,003 times

1

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

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

And in mine it’s like this:

inserir a descrição da imagem aqui

How could I reproduce the same behavior?

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:


Example of use:

// 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:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.