create a picker that saves the selection to a new variable in swift

To create a picker in Swift, follow these steps:

  1. Create a UIPickerView instance and add it to your view. For example, you can add it to a UIViewController's view in the viewDidLoad() method:
main.swift
let pickerView = UIPickerView()
view.addSubview(pickerView)
60 chars
3 lines
  1. Implement the UIPickerViewDataSource and UIPickerViewDelegate protocols. These protocols provide methods for setting the number of components in the picker, the number of rows in each component, and the title for each row. For example:
main.swift
class MyViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
    
    let items = ["Item 1", "Item 2", "Item 3"]
    var selectedValue: String?
    
    // ...

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return items.count
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return items[row]
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectedValue = items[row]
    }
    
}
716 chars
25 lines

In this example, we have an array of items and a selectedValue variable that will hold the selected item. The numberOfComponents() method returns 1 since we only have one column in the picker. The numberOfRowsInComponent() method returns the number of items in the array, and the titleForRow() method returns the title for each row based on the item's index in the array. Finally, the didSelectRow() method sets the value of the selectedValue variable to the selected item.

  1. Set the picker's dataSource and delegate properties to your view controller:
main.swift
pickerView.dataSource = self
pickerView.delegate = self
56 chars
3 lines

Now your UIPickerView is set up and ready to use. When the user selects an item, the selectedValue variable will be updated with the selected item's value.

gistlibby LogSnag