6

i am using alert with a textfield input to save the data, what i want to know is i wanted to add a date picker to the alert so that the user will add name and then date. i have already made it possible saving the name but i am having trouble on adding date picker code and how would it be added to an alert. the code is below.

code of the alert:

if indexPath.row == 0 {
    let alert = UIAlertController(title: "Add New Chore", message: "", preferredStyle:
        UIAlertControllerStyle.alert)

    //this is the field where the user add the name
    alert.addTextField(configurationHandler: textFieldHandler)

    let a =  loggedInUsername
    if ((a?.lowercased().range(of: "mother")) != nil) {
        print("true")
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in

            let newItem : String = (alert.textFields?.first?.text)!
            if !newItem.isEmpty {

                let item = Item(name: newItem)
//                        let item2 = Item(name: newItem2)
                self.saveItemInLocalDB(groceryItem: item!)

                self.setUpCollectionView()

            }
        }))

code for saving to local db using core data:

func saveItemInLocalDB(groceryItem : Item) {
    let context = getContext()

    //retrieve the entity that we just created
    let entity =  NSEntityDescription.entity(forEntityName: "GroceryItem", in: context)

    let item = NSManagedObject(entity: entity!, insertInto: context)

    //set the entity values
    item.setValue(groceryItem.name, forKey: "name")
    item.setValue(false, forKey: "isSelected")
    item.setValue(loggedInUserHouseNumber, forKey: "houseNo")

    //save the object
    do {
        try context.save()
        print("ang item:", groceryItem.name)
        print("saved!")
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    } catch {

    }
}
Bista
  • 7,869
  • 3
  • 27
  • 55

3 Answers3

13

Adding Date Picker to an alert in Swift 5

    let myDatePicker: UIDatePicker = UIDatePicker()
    myDatePicker.timeZone = .local
    myDatePicker.preferredDatePickerStyle = .wheels
    myDatePicker.frame = CGRect(x: 0, y: 15, width: 270, height: 200)
    let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n", message: nil, preferredStyle: .alert)
    alertController.view.addSubview(myDatePicker)
    let selectAction = UIAlertAction(title: "Ok", style: .default, handler: { _ in
        print("Selected Date: \(myDatePicker.date)")
    })
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    alertController.addAction(selectAction)
    alertController.addAction(cancelAction)
    present(alertController, animated: true)
Ahmadreza
  • 6,950
  • 5
  • 50
  • 69
2

Hello You can use this code:

Step:-1 Take Variable at Top:

var datePicker:UIDatePicker = UIDatePicker()
let toolBar = UIToolbar()

Step:-2 Create alert with textfield:

    //1. Create the alert controller.
    let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)

    //2. Add the text field. You can configure it however you need.
    alert.addTextField { (textField) in
        self.doDatePicker()
        textField.inputView = self.datePicker
        textField.inputAccessoryView = self.toolBar
    }

    // 3. Grab the value from the text field, and print it when the user clicks OK.
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
        let textField = alert?.textFields![0] // Force unwrapping because we know it exists.
        if textField?.text != ""{
            print("Text field: \(textField?.text!)")
        }
    }))

    // 4. Present the alert.
    self.present(alert, animated: true, completion: nil)

Step:-3 Call this functions

func doDatePicker(){
    // DatePicker
  // datePicker = UIDatePicker()

    self.datePicker = UIDatePicker(frame:CGRect(x: 0, y: self.view.frame.size.height - 220, width:self.view.frame.size.width, height: 216))
    self.datePicker.backgroundColor = UIColor.white
    datePicker.datePickerMode = .date

    // ToolBar

    toolBar.barStyle = .default
    toolBar.isTranslucent = true
    toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
    toolBar.sizeToFit()

    // Adding Button ToolBar
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(HomeNewVC.doneClick))
    let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(HomeNewVC.cancelClick))
    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: true)
    toolBar.isUserInteractionEnabled = true

    self.toolBar.isHidden = false

}


@objc func doneClick() {
    let dateFormatter1 = DateFormatter()
    dateFormatter1.dateStyle = .medium
    dateFormatter1.timeStyle = .none

    datePicker.isHidden = true
    self.toolBar.isHidden = true
}

@objc func cancelClick() {
    datePicker.isHidden = true
    self.toolBar.isHidden = true
}

Although Thing is ok to work, but in real time we should avoid using datepicker in alertview.

Note:- Instead of it make a pop-up window or else use .xib file and inside it take 2 textfields and then use one as name and second as date-picker.

Or else You can also use this Third party support which somewhat matches your requirement :- Alert Modifications

Abhirajsinh Thakore
  • 1,806
  • 2
  • 13
  • 23
2

Using the 'blank new lines' trick you can achieve this in Swift 5 by doing:

let datePicker = UIDatePicker()
datePicker.frame = CGRect(x: 0, y: 40, width: 270, height: 200)

let alert = UIAlertController(title: "TITLE", message: "\n\n\n\n\n\n\n\n\n", preferredStyle: .alert)
alert.view.addSubview(datePicker)

let selectAction = UIAlertAction(title: "OK", style: .default, handler: { _ in
    print("Selected Date: \(datePicker.date)")
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

alert.addAction(selectAction)
alert.addAction(cancelAction)

present(alert, animated: true)

It looks good but keep in mind it's hacky and can break in the future

Radu Ursache
  • 1,230
  • 1
  • 22
  • 35