Display datepicker on tapping on textfield
You can use inputView
and inputAccessoryView
properties of the text field for this. Create the date picker and set it to the input views of the two text fields. Also create another view for the Done
button and it as their accessory view. You will need that button to dismiss the input view.
The Done
button must be wired up to function which basically does this –
if ( [textField1 isFirstResponder] ) {
[textField1 resignFirstResponder];
} else if ( [textField2 isFirstResponder] ) {
[textField2 resignFirstResponder];
}
Another option would be to subclass UITextField
and override inputView
and inputAccessoryView
. This is the way to go when there are loads of them.
Example
@interface CustomKeyboardAppDelegate : NSObject <UIApplicationDelegate> {
...
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UITextField *textField;
@property (nonatomic, retain) IBOutlet UIToolbar *accessoryView;
@property (nonatomic, retain) IBOutlet UIDatePicker *customInput;
- (IBAction)dateChanged:(id)sender;
- (IBAction)doneEditing:(id)sender;
@end
In the XIB, Pull out a UIToolbar
and a UIDatePicker
but don't attach it to the view. Connect the outlets appropriately. dateChanged:
responds to changes in the date picker and doneEditing:
is called when the Done
button in the tool bar is clicked. Connect them too. The methods are implemented as listed below.
@implementation CustomKeyboardAppDelegate
@synthesize window=_window;
@synthesize textField = _textField;
@synthesize accessoryView = _accessoryView;
@synthesize customInput = _customInput;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.textField.inputView = self.customInput;
self.textField.inputAccessoryView = self.accessoryView;
...
}
...
- (IBAction)dateChanged:(id)sender {
UIDatePicker *picker = (UIDatePicker *)sender;
self.textField.text = [NSString stringWithFormat:@"%@", picker.date];
}
- (IBAction)doneEditing:(id)sender {
[self.textField resignFirstResponder];
}
@end
The last two methods will bloat up as more text fields depend on this picker.
Show datepicker on textfield tap
UIResponder
, from which UITextField
inherits, defines a property called inputView
. This property (a UIView *
) can define a view that will be displayed instead of the keyboard when that UIResponder
becomes the first responder.
Thus, if you want a UIDatePicker
to appear when you tap in a textField (ie, you make that textField the first responder), then you can say, naïvely:
UIDatePicker *datePicker = [[UIDatePicker alloc] init...];
... configure datePicker ...
[myTextField setInputView:datePicker];
Now, when your UITextField
is tapped, a UIDatePicker
will be brought up instead.
HOWEVER
You'll want to do more than this, because you'll need to handle different orientations and different idioms.
But that's the basic idea.
(And if you want a toolbar above the UIDatePicker
, that's what the inputAccessoryView
property is for...)
How to bring up a date picker when a date field is tapped?
I guess you are taking a UITextField
for the input but you have not established a connection between the datePicker and textfield.
Have a look at this answer here
In swift this can be done by textfield.inputView = datePickerView
. After this the click on textfield will be handled by datePicker, but you should initialize datePicker before doing this.
how do i show date picker when clicked on textfield
override func viewDidLoad(){
super.viewDidLoad()
picker.isHidden = true
txt3.delegate = self
//self.txt3.inputView = picker // don't do this
self.txt3.inputView = datePicker // do like this.
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.doneButton))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.doneButton)
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
txt3.inputAccessoryView = toolBar
}
func doneButton(){
let selectedDate = datePicker.date
print(selectedDate)
txt3.resignFirstResponder()
}
It will automatically open the date picker.
How to get flutter datepicker value to the textfield?
I fix your code as below (you can select date from DatePicker and you can customise theme of DatePicker):
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class TestPickerWidget extends StatefulWidget {
@override
_TestPickerWidgetState createState() => _TestPickerWidgetState();
}
class _TestPickerWidgetState extends State<TestPickerWidget> {
DateTime _selectedDate;
TextEditingController _textEditingController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextField(
focusNode: AlwaysDisabledFocusNode(),
controller: _textEditingController,
onTap: () {
_selectDate(context);
},
),
),
);
}
_selectDate(BuildContext context) async {
DateTime newSelectedDate = await showDatePicker(
context: context,
initialDate: _selectedDate != null ? _selectedDate : DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2040),
builder: (BuildContext context, Widget child) {
return Theme(
data: ThemeData.dark().copyWith(
colorScheme: ColorScheme.dark(
primary: Colors.deepPurple,
onPrimary: Colors.white,
surface: Colors.blueGrey,
onSurface: Colors.yellow,
),
dialogBackgroundColor: Colors.blue[500],
),
child: child,
);
});
if (newSelectedDate != null) {
_selectedDate = newSelectedDate;
_textEditingController
..text = DateFormat.yMMMd().format(_selectedDate)
..selection = TextSelection.fromPosition(TextPosition(
offset: _textEditingController.text.length,
affinity: TextAffinity.upstream));
}
}
}
class AlwaysDisabledFocusNode extends FocusNode {
@override
bool get hasFocus => false;
}
and also you must add Intl dependency in your pubspec.yaml :
dev_dependencies:
flutter_test:
sdk: flutter
intl: ^0.16.1
Finally call TestPickerWidget in your main for testing it.
I want in one textfield it can be show keyboard and datepicker
You've to try this
class yourViewController: UIViewController,UITextFieldDelegate
{
var screenHeight = UIScreen.main.bound.height
var screenWidth = UIScreen.main.bound.width
var dateFormatter = DateFormatter()
var doneButton = UIBarButtonItem()
var cancelButton = UIBarButtonItem()
var timeValueLabel = UIBarButtonItem()
var datePicker : UIDatePicker!
var toolBarDtPicker = UIToolbar()
//MARK:- Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
yourTxtField.delegate = self
}
//TextField Editing Begin Function
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool
{
self.hideKeyboard()
textField.inputView = nil
textfieldEding(sender: textField)
return false
}
//To Hide Keyboard
@objc func hideKeyboard()
{
UIApplication.shared.sendAction(#selector(UIApplication.resignFirstResponder), to: nil, from: nil, for: nil)
}
//DatePicker Function
func datePickerView()
{
if ((self.datePicker != nil) && (self.datePicker.superview != nil))
{
datePicker.removeFromSuperview()
}
self.datePicker = UIDatePicker(frame: CGRect(x: 0, y:
UIScreen.main.bounds.height-200, width: UIScreen.main.bounds.width, height: 200))
self.datePicker.backgroundColor = UIColor.white
self.datePicker.addTarget(self, action: #selector(dateHandler), for: .valueChanged)
self.view.addSubview(datePicker)
toolBarDtPicker = UIToolbar(frame: CGRect(x: 0, y: screenHeight-230, width: screenWidth, height: 30))
toolBarDtPicker.barStyle = .default
toolBarDtPicker.isTranslucent = false
toolBarDtPicker.barTintColor = UIColor.blue
toolBarDtPicker.sizeToFit()
// Adding Button ToolBar
doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneClick))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
timeValueLabel = UIBarButtonItem(title: " ", style: .plain, target: self, action: nil)
let spaceButton2 = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelClick))
doneButton.tintColor = UIColor.white
timeValueLabel.tintColor = UIColor.white
cancelButton.tintColor = UIColor.white
toolBarDtPicker.setItems([cancelButton, spaceButton, timeValueLabel, spaceButton2, doneButton], animated: true)
toolBarDtPicker.isUserInteractionEnabled = true
self.view.addSubview(toolBarDtPicker)
self.toolBarDtPicker.isHidden = false
datePicker.datePickerMode = .date
dateFormatter.dateStyle = .medium
dateFormatter.dateFormat = "EEEE dd MMM yyyy"
}
@objc func textfieldEding(sender: UITextField)
{
datePickerView()
}
@IBAction func showKeyBoard(_ sender: UIButton!)
{
self.yourTxtField.becomeFirstResponder()
}
//MARK: DatePicker
@objc func dateHandler(sender: UIDatePicker)
{
dateFormatter.dateFormat = "EEEE dd MMM yyyy"
timeValueLabel.title = dateFormatter.string(from: sender.date)
}
@objc func doneClick() //DatePIcker Done Button
{
//Done Button Code
}
//MARK: Cancel Btn
@objc func cancelClick() //DatePIcker Cancel Button
{
if ((self.datePicker != nil) && (self.datePicker.superview != nil))
{
datePicker.removeFromSuperview()
}
toolBarDtPicker.removeFromSuperview()
}
}
displaying datepicker on the tap of a particular text field only
If you have your UITextField as an attribute of the class simply check it on the delegate method
- (BOOL) textFieldShouldBeginEditing: (UITextField*) textField {
if (textField == _datePickerField) {
// Show picker
}
}
If not, UITextField is a subclass of UIView. You can tag it when created with the value of an enumeration and then, on the delegate method check the tag. If the textField you are editing is the one who raises the DatePicker, do it.
enum {
iee_Field1 = 0,
iee_Field2,
iee_DatePcikerField
};
- (BOOL) textFieldShouldBeginEditing: (UITextField*) textField {
if (textField.tag == iee_DatePickerField) {
// Show picker
}
}
DatePicker opening on second click on TextField
Make first responder on button click
@IBAction func eodAction(_ sender: UITextField) {
deregisterFromKeyboardNotifications()
self.button.isHidden=true
eodDateTime.becomeFirstResponder()
// self.pickUpDate(eodDateTime)
}
And implement textFieldShouldBeginEditing
method to show date picket in input view
extension ATMDiscrepancyViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if textField == eodDateTime {
self.pickUpDate(eodDateTime)
}
}
}
Related Topics
How to Change Font of Uibutton with Swift
How to Deselect a Selected Uitableview Cell
Scrollview and Keyboard in Swift
Change the Font of a Uibarbuttonitem
Width and Height Equal to Its Superview Using Autolayout Programmatically
How to Change Height of Grouped Uitableview Header
Differencebetween the App Id and the Bundle Id? Where Is the App Id in the Xcode Project
Frosted Glass (iOS 7 Blur) Effect
How to Convert Nsinteger to Nsstring Datatype
Pod Install Displaying Error in Cocoapods Version 1.0.0.Beta.1
How to Dismiss Keyboard When Touching Anywhere Outside Uitextfield (In Swift)
Should I Be Using Awakefromnib or Initwithcoder Here
How to Set Multi Line Large Title in Navigation Bar? ( New Feature of iOS 11)
Transparent Uinavigationbar in Swift
Xcode 8: Preparing Archive Takes Forever
Code Sign Error on Xcode 8 and iOS 10 Cordova Project
Uisearchdisplaycontroller's Searchresultstableview's Contentsize Is Incorrect. Bug in iOS 7