To open a date picker in textFieldShouldBeginEditing we can use the inpuView property of the textField.
To open a datePicker when text Field start editing we can follow these steps.
1- On your View Controller add a view that contains the our UIDatePicker and two buttons(Cancel and Done).
2- Also add two textField one will open the normal keyBoard and other textField will open the datePicker.
3- Create the IBOutlet for the datePickerSuperView,datePicker,keyTextField,dateTextField.
4- Connect these for outlet .
5- Set the textField delegate methods.
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var datePickerSuperview: UIView!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var keyTextField: UITextField!
@IBOutlet weak var dateTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
datePickerSuperview.removeFromSuperview()
datePickerSuperview.hidden = true
dateTextField.inputView = datePickerSuperview
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnDoneTapped(sender:UIButton){
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
dateTextField.text = dateFormatter.stringFromDate(datePicker.date) as String
self.view.endEditing(true)
}
@IBAction func btnCancelTapped(sender:UIButton){
datePickerSuperview.hidden = true
dateTextField.text = ""
self.view.endEditing(true)
}
//MARK : TextField Delegate
func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
{
datePickerSuperview.hidden = true
self.view.endEditing(true);
return true;
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if textField == dateTextField {
datePickerSuperview.hidden = false
}
return true
}
}
0 Comment(s)