Search code examples
iosswiftuitextfielduipickerview

How to populate UITextField with UIPickerView that have 3 components?


I did a date customized UIPickerView in my ViewController that have 3 components.

This picker work as an input to a UITextField. See some parts of my code to check how it was implemented.

var dataDia1: NSMutableArray!
var dataMes1: NSMutableArray!
var dataAno1: NSMutableArray!

@IBOutlet weak var pickerTextFieldInicio: UITextField!

let pickerViewInicio = UIPickerView()

override func viewDidLoad() {
    super.viewDidLoad()

    // Declaração dos Picker

    pickerViewInicio.delegate = self
    pickerViewInicio.dataSource = self
    pickerViewInicio.showsSelectionIndicator = true
    pickerViewInicio.backgroundColor = UIColor(red: 255/255, green: 193/255, blue: 193/255, alpha: 1)

    self.dataDia1 = NSMutableArray()

    for dia in 1...31
    {
        dataDia1.addObject("\(dia)")
    }

    self.dataMes1 = NSMutableArray()

    for mes in 1...12
    {
        dataMes1.addObject("\(mes)")
    }

    self.dataAno1 = NSMutableArray()

    for ano in 1970...2016
    {
        dataAno1.addObject("\(ano)")
    }

    pickerTextFieldInicio.inputView = pickerViewInicio

My question is, how can I populate pickerTextFieldInicio with something like 31/10/2015?

I checked some posts realeted to Objective C, but I could not solve my problem as I'm using Swift.

Thanks.


Solution

  • Add a UIDatePicker to the MainStoryBoardand then create an @IBOutlet for the UIDatePicker in the ViewController.swift name it whatever you want for instance we will use diaPicked

    Next create an @IBOutlet for an UILabel and name it. Create a @IBAction for the DatePicker and name it. For intance let's say that we called it pickerAction Inside of the pickerAction add

    @IBAction func PickerAction(sender: AnyObject) {
    
        var diaFormato = NSDateFormatter()
        diaFormato.dateFormat = "dd-MM-yyyy HH:mm"
        var strDate = diaFormato.stringFromDate(diaPicked.date)
        self.selectedDate.text = strDate
    
    }
    

    I see that your variables are in spanish so I'll translate it for you since I speak spanish,

    Agrega un UIDatePicker al MainStoryBoard y crea un @IBOutlet para el UIDatePicker en el ViewController.swift y lo puedes llamar lo que quieras pero por este ejemplo vamos a user Dias. y despues crea otro IBOutlet y le llamas diaSelecionado

    Después crea un @IBAction para Dias y le llamas diasSelecionadoAcion que salga del UIDatePicker llamado Dias

       @IBAction func Dias (sender: AnyObject) {
        var diaFormato = NSDateFormatter()
        diaFormato.dateFormat = "dd-MM-yyyy HH:mm"
        var strDate = diaFormato.stringFromDate(diaPicked.date)
        self.diaSelecionado.text = strDate
        }