Search code examples
iosswiftuitextfieldtimepicker

Unable to add time picker time to textfield in swift


I have created time picker in alert and in ok action i want to add selected time to regarding textfield, and is it possible to hide AM, PM from time picker, if possible how? i need to show only hours and minutes without AM, PM in time picker. please help me in the code.

here is my code:

 func timePicker(){

    let vc = UIViewController()
    vc.preferredContentSize = CGSize(width: 200,height: 200)
    let timePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    let dateFormatter = DateFormatter()
    //dateFormatter.dateFormat = "HH:mm"
    timePicker.datePickerMode = .time

    vc.view.addSubview(timePicker)
    let addTimePickerAlert = UIAlertController(title: "", message: "", preferredStyle: UIAlertController.Style.alert)

    addTimePickerAlert.setValue(vc, forKey: "contentViewController")
    let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in

        self.hoursMinutesTextField.text = dateFormatter.string(from: timePicker.date)
        print("time textfield \(self.hoursMinutesTextField.text)")
    })
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: {
        (action : UIAlertAction!) -> Void in
    })
    addTimePickerAlert.addAction(ok)
    addTimePickerAlert.addAction(cancelAction)

    self.present(addTimePickerAlert, animated: true)
}

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool 
{

 self.timePicker()
    return true
}

please help me in the code


Solution

  • You missed set dateFormat to dateFormatter that's why you getting " "

    Uncomment this line in your code its work

    dateFormatter.dateFormat = "hh:mm" // 04:57
    
    dateFormatter.dateFormat = "HH:mm" // 16:57
    

    Output:

    enter image description here