Add Done Button On UIDatePicker
by sisccr
Default UIDatePicker View has a default Done button when it is displayed. But It does not work by default.
If you are using the textField delegate, It is simple. Ios provides us a delegate function that is called when Return key is pressed.
func textFieldShouldReturn(textField: UITextField) -> Bool { // done button clicked }
But my requirement don’t allows us to use delegate, so I need another way.
So, we need to add an button. I will be adding button pragmatically but we can also use the storyboard.
I already have textField which shows datePicker when selected.
after setting up the textField and datePicker, a function is called to add the “Done” button.
func setUpDoneButton() { let toolBar = UIToolbar() toolBar.barStyle = .Default toolBar.translucent = true let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) let doneButton = UIBarButtonItem(title: "Done", style: .Done, target: self, action: #selector(doneDatePickerPressed(_:))) doneButton.tintColor = UIColor.blackColor() toolBar.setItems([space, doneButton], animated: false) toolBar.userInteractionEnabled = true toolBar.sizeToFit() addDoneButtonToDatePickers(toolBar) }
after setting up the button addDoneButtonToDatePickers function is called.
func addDoneButtonToDatePickers(doneButton: UIToolbar) { addDoneButtonToDatePickerView(txtStartDate, doneButton: doneButton) addDoneButtonToDatePickerView(txtEndDate, doneButton: doneButton) }
func addDoneButtonToDatePickerView(textField: UITextField, doneButton: UIToolbar) { textField.inputAccessoryView = doneButton }
When Done button is touched, doneDatePickerPressed function is called.
func doneDatePickerPressed(sender: UIBarButtonItem) { print("done button clicked.") self.view.endEditing(true) }
Awesome :). Just a thought …for me to read #setUpDoneButton codes I need to squiz :)..
LikeLike
squeezing idea is of great dime,
But currently I don’t have that much time 🙂 …
LikeLike
Follow some easy way dude ..
space constant is crossing 125 horizontal line.. I think it should be no more than 80 line :)..
BTW great tutorial 🙂
LikeLike
Yeah! But Thats for notepad and text editor. I did thought of that too but its hard to write anything under 80 line on swift. I think its better to write function’s signature in one line instead of multiline. Anyways, thanks for the tips. 🙂
LikeLike
I have updated the post. Thought you wanna check it out, still not under 80 lines thought. 😛
LikeLiked by 1 person
Great 🙂 .. Looks solid 🙂
LikeLike