hi i am new to iphone programming .This program i will be doing for iphone so i want help. My question is by clicking a button can date picker appear and the when the date is chosen , i want it to be stored in a text field.How it can be done . kindly help me.I shall be very thankful to you. i had a button on which i want to show a date time picker how it can be done ?
below is my try code but it is not working just showing black screen.
- (IBAction)date:(id)sender {
UIDatePicker* picker = [[UIDatePicker alloc] init];
picker.autoresizingMask = UIViewAutoresizingFlexibleWidth;
picker.datePickerMode = UIDatePickerModeDate;
[picker addTarget:self action:#selector(dueDateChanged:) forControlEvents:UIControlEventValueChanged];
CGSize pickerSize = [picker sizeThatFits:CGSizeZero];
picker.frame = CGRectMake(0.0, 250, pickerSize.width, 460);
picker.backgroundColor = [UIColor blackColor];
[self.view addSubview:picker];
// [picker release];
}
-(void) dueDateChanged:(UIDatePicker *)sender {
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
//self.myLabel.text = [dateFormatter stringFromDate:[dueDatePickerView date]];
NSLog(#"Picked the date %#", [dateFormatter stringFromDate:[sender date]]);
}
Your CGSizeZero is probably causing your date picker to not show.
This is how I do it in a simple way:
.H file
#interface ViewController : UIViewController
#property (nonatomic, strong) UIDatePicker *datePicker;
#property (nonatomic, strong) UITextField *textField;
#property (nonatomic, strong) UIButton *btnShowPicker;
#end
.M file
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self initViews];
}
-(void)initViews
{
self.datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 20, 280, 200)];
// hide date picker at first
self.datePicker.alpha = 0;
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(20, self.datePicker.frame.origin.y + self.datePicker.frame.size.height + 20, self.view.frame.size.width - 40.0, 35)];
self.textField.layer.borderWidth = 1.0;
self.textField.layer.borderColor = [UIColor grayColor].CGColor;
self.textField.textAlignment = NSTextAlignmentCenter;
self.btnShowPicker = [[UIButton alloc] initWithFrame:CGRectMake(20, self.view.bounds.size.height - 140.0, self.view.frame.size.width - 40.0, 50.0)];
[self.btnShowPicker setTitle:#"Show Date Picker" forState:UIControlStateNormal];
self.btnShowPicker.backgroundColor = [UIColor blueColor];
[self.btnShowPicker addTarget:self action:#selector(showDatePicker:) forControlEvents:UIControlEventTouchUpInside];
self.btnDone = [[UIButton alloc] initWithFrame:CGRectMake(self.btnShowPicker.frame.origin.x, self.btnShowPicker.frame.origin.y + self.btnShowPicker.frame.size.height + 10.0, self.btnShowPicker.frame.size.width, self.btnShowPicker.frame.size.height)];
self.btnDone.backgroundColor = [UIColor greenColor];
[self.btnDone setTitle:#"Done" forState:UIControlStateNormal];
[self.btnDone addTarget:self action:#selector(datePicked) forControlEvents:UIControlEventTouchUpInside];
self.btnDone.alpha = 0;
[self.view addSubview:self.datePicker];
[self.view addSubview:self.textField];
[self.view addSubview:self.btnShowPicker];
[self.view addSubview:self.btnDone];
}
-(void)showDatePicker:(id)sender
{
self.datePicker.alpha = 1.0;
self.btnDone.alpha = 1.0;
}
-(void)datePicked
{
if(self.datePicker.alpha != 0)
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy HH:mm:ss"];
// populate the text field with new date
self.textField.text = [dateFormatter stringFromDate:self.datePicker.date];
}
}
Now when you scroll the date picker, you get the date populated in your text field like this:
Related
I have created a row of UIButtons and added one week's date and day as UILabel on it. I have also created a UIView selector that when the button is selected, it will highlight the whole button.
Now I am stuck with how to add a separator or vertical lines between the buttons. And instead of highlighting the UIButton I wish to change the text colour to blue when the button is selected. Please help
What I have created
what i am trying to achieve
Code
CGFloat HEIGHT_BTN = 55.0; //--- 10 pixels from the navigation view
CGFloat HEIGHT_LABEL = 30.0;
CGFloat HEIGHT_LABEL2 = 15.0;
-(void)setupSegmentButtons
{
CGFloat Y_POS_BTN = [[UIApplication sharedApplication] statusBarFrame].size.height+5;
//=== The view where the buttons sits
navigationView = [[UIView alloc]initWithFrame:CGRectMake(0,Y_POS_BTN,self.view.frame.size.width,HEIGHT_BTN)];
navigationView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:navigationView]; //=== Create a View called navigationView
//==== Setup the shadows
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:self.navigationView.bounds];
self.navigationView.layer.masksToBounds = NO;
self.navigationView.layer.shadowColor = [UIColor lightGrayColor].CGColor;
self.navigationView.layer.shadowOffset = CGSizeMake(5.0f, 5.0f);
self.navigationView.layer.shadowOpacity = 0.8f;
self.navigationView.layer.shadowPath = shadowPath.CGPath;
//=== Get the dates and formatting of the dates
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *beginningOfThisWeek;
NSTimeInterval durationOfWeek;
[calendar rangeOfUnit:NSWeekCalendarUnit
startDate:&beginningOfThisWeek
interval:&durationOfWeek
forDate:now];
NSDateComponents *comps = [calendar components:NSUIntegerMax fromDate:now];
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/YYYY"];
NSDateFormatter *datelblFormat = [[NSDateFormatter alloc] init];
[datelblFormat setDateFormat:#"dd"];
NSDateFormatter *daylblFormat= [[NSDateFormatter alloc] init];
[daylblFormat setDateFormat:#"EEE"];
//=== Loop 7 times to create the Buttons and the 2 lines Labels
for (int i = 0; i<numControllers; i++) {
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(i*(self.navigationView.frame.size.width/numControllers), 0, (self.navigationView.frame.size.width/numControllers),HEIGHT_BTN)];
[navigationView addSubview:button]; //=== Put the buttons into the navigation View
NSString *dateString = [dateFormatter stringFromDate:[calendar dateFromComponents:comps]];
[dtDate addObject:dateString];
NSString *lblDate = [datelblFormat stringFromDate:[calendar dateFromComponents:comps]];
firstLineButton = [[UILabel alloc] initWithFrame:CGRectMake(0,5,self.view.frame.size.width/numControllers,HEIGHT_LABEL)];
firstLineButton.text = lblDate;
firstLineButton.font = [UIFont systemFontOfSize:20];
firstLineButton.textColor = [UIColor whiteColor];
firstLineButton.textAlignment=NSTextAlignmentCenter;
[button addSubview:firstLineButton]; //=== Put the Date in the 1st line of the the button
NSString *lblDay = [daylblFormat stringFromDate:[calendar dateFromComponents:comps]];
UILabel *secondLineButton = [[UILabel alloc] initWithFrame:CGRectMake(0,28,self.view.frame.size.width/numControllers,HEIGHT_LABEL2)];
secondLineButton.text = lblDay;
secondLineButton.textColor = [UIColor whiteColor];
secondLineButton.font = [UIFont boldSystemFontOfSize:11];
secondLineButton.textAlignment=NSTextAlignmentCenter;
[button addSubview:secondLineButton]; //=== Put the Day in the 2nd line of the Button
button.tag = i; //--- IMPORTANT: if you make your own custom buttons, you have to tag them appropriately
button.backgroundColor = [UIColor colorWithRed:236.0f/255.0f green:0/255.0f blue:140.0f/255.0f alpha:0.6];//%%% buttoncolors
[button addTarget:self action:#selector(tapSegmentButtonAction:) forControlEvents:UIControlEventTouchUpInside];
++comps.day;
}
[self setupSelector]; //=== The selection bar or highligthed area
}
//=== sets up the selection bar under the buttons or the highligted buttons on the navigation bar
-(void)setupSelector {
//CGFloat Y_POS_BTN = [[UIApplication sharedApplication] statusBarFrame].size.height+5;
selectionBar = [[UIView alloc]initWithFrame:CGRectMake(0, Y_BUFFER, (self.view.frame.size.width/numControllers),HEIGHT_BTN)];
selectionBar.backgroundColor = [UIColor colorWithRed:236.0f/255.0f green:0/255.0f blue:140.0f/255.0f alpha:0.6]; //%%% sbcolor
//selectionBar.alpha = 0.8; //%%% sbalpha
[navigationView addSubview:selectionBar];
}
//=== When the top button is tapped
#pragma mark Setup
-(void)tapSegmentButtonAction:(UIButton *)button {
sDtDate = dtDate[button.tag];
[self LoadClasses];
__weak typeof(self) weakSelf = self;
[weakSelf updateCurrentPageIndex:button.tag];
NSInteger xCoor = selectionBar.frame.size.width*self.currentPageIndex;
selectionBar.frame = CGRectMake(xCoor, selectionBar.frame.origin.y, selectionBar.frame.size.width, selectionBar.frame.size.height);
}
Well, I'll prefer a more elegant way to achieve this.
First, create a UIButton subclass (let's say WeekdayButton) which will generate an attributed title from NSDate and configure so it is able to display a multiline title with different fonts.
WeekdayButton.h
#import <UIKit/UIKit.h>
#interface WeekdayButton : UIButton
#property (strong, nonatomic) NSDate *date;
#end
WeekdayButton.m
#import "WeekdayButton.h"
#implementation WeekdayButton
static NSDateFormatter *dayFormatter;
static NSDateFormatter *weekFormatter;
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
[self setup];
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
[self setup];
}
- (void)setup {
self.titleLabel.numberOfLines = 2;
self.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.titleLabel.textAlignment = NSTextAlignmentCenter;
self.backgroundColor = [UIColor colorWithRed:236.0f/255.0f green:0/255.0f blue:140.0f/255.0f alpha:0.6];
}
- (void)setDate:(NSDate *)date {
_date = date;
NSAttributedString *normalTitle = [self generateNormalTitle];;
NSAttributedString *selectedTitle = [self generateSelectedTitle];
[self setAttributedTitle:normalTitle forState:UIControlStateNormal];
[self setAttributedTitle:selectedTitle forState:UIControlStateSelected];
}
- (NSAttributedString *)generateNormalTitle {
NSMutableAttributedString *result = [NSMutableAttributedString new];
if (!dayFormatter) {
dayFormatter = [NSDateFormatter new];
dayFormatter.dateFormat = #"dd";
}
if (!weekFormatter) {
weekFormatter = [NSDateFormatter new];
weekFormatter.dateFormat = #"EEE";
}
NSString *day = [[dayFormatter stringFromDate:self.date] stringByAppendingString:#"\n"];
NSString *week = [weekFormatter stringFromDate:self.date];
[result appendAttributedString:[[NSAttributedString alloc] initWithString:day
attributes:#{NSFontAttributeName:[UIFont systemFontOfSize:20]}]];
[result appendAttributedString:[[NSAttributedString alloc] initWithString:week
attributes:#{NSFontAttributeName:[UIFont boldSystemFontOfSize:11]}]];
[result addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, result.length)];
return result;
}
- (NSAttributedString *)generateSelectedTitle {
NSMutableAttributedString *result = [[self generateNormalTitle] mutableCopy];
[result addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, result.length)];
return result;
}
#end
Then in your ViewController make a horizontal UIStackView, generate 7 WeekdayButton button and pass NSDate object starting from today.
ViewController.m
#import "ViewController.h"
#import "WeekdayButton.h"
#interface ViewController ()
#property (strong, nonatomic) UIStackView *stackView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupWeekDayButtons];
}
- (void)setupWeekDayButtons {
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 40, self.view.frame.size.width, 55)];
containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self.view addSubview:containerView];
containerView.layer.shadowRadius = 5;
containerView.layer.shadowColor = [UIColor blackColor].CGColor;
containerView.layer.shadowOpacity = 0.5;
containerView.layer.shadowOffset = CGSizeMake(0, 5);
self.stackView = [[UIStackView alloc] initWithFrame:containerView.bounds];
self.stackView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.stackView.axis = UILayoutConstraintAxisHorizontal;
self.stackView.distribution = UIStackViewDistributionFill;
self.stackView.spacing = 0;
[containerView addSubview:self.stackView]; //Embeding stackview in a UIView cause UIStackView can't draw shadow.
int numberOfDays = 7;
for (int i = 0; i < numberOfDays; i++) {
NSDate *date = [[NSDate date] dateByAddingTimeInterval:i * 24 * 3600];
WeekdayButton *button = [WeekdayButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:#selector(weekDayTapped:) forControlEvents:UIControlEventTouchUpInside];
button.date = date;
button.translatesAutoresizingMaskIntoConstraints = NO;
[self.stackView addArrangedSubview:button];
[button.widthAnchor constraintEqualToAnchor:self.stackView.widthAnchor
multiplier:1/(CGFloat)numberOfDays].active = YES;
if (i != numberOfDays - 1) {
UIView *separator = [UIView new];
separator.translatesAutoresizingMaskIntoConstraints = NO;
separator.backgroundColor = [UIColor whiteColor];
[button addSubview:separator];
[separator.widthAnchor constraintEqualToConstant:1].active = true;
[separator.trailingAnchor constraintEqualToAnchor:button.trailingAnchor constant:0].active = YES;
[separator.centerYAnchor constraintEqualToAnchor:button.centerYAnchor constant:0].active = YES;
[separator.heightAnchor constraintEqualToAnchor:button.heightAnchor multiplier:1 constant:-20].active = YES;
}
}
}
- (void)weekDayTapped:(WeekdayButton *)sender {
[self.stackView.arrangedSubviews makeObjectsPerformSelector:#selector(setSelected:) withObject:nil]; //Deselecting all buttons
sender.selected = YES;
NSLog(#"Selected: %#", sender.date);
//TODO: Do your logic after selection here
}
#end
Here is the result:
I here provide an answer with the power of stack view and auto layout
The code will be limited and you can customized almost everything in IB.
Tint color of buttons may needs care when setting selected state.
-(IBAction)selector:(id)sender{
UIButton * button = (UIButton *)sender;
[button setSelected: !button.isSelected ];
}
setting in IB
selected State
topstackview
second stack view
Use this idea, you can build your example much faster and safe.
For: "how to add a separator or vertical lines between the buttons":
After [button addSubview:secondLineButton]; //=== Put the Day in the 2nd line of the Button add a view as separator
if (i < (numControllers - 1)){
UIView *separator = [[UIView alloc] initWithFrame:CGRectMake(button.frame.size.width - 1, 5, 1, button.frame.size.height - 10))];
separator.backgroundColor = UIColor.whiteColor
[button addSubview:separator];
}
For text color, create: btnCurrentSelected and:
#interface YouClass : UIViewController
{
UIButton *btnCurrentSelected;
}
-(void)tapSegmentButtonAction:(UIButton *)button {
sDtDate = dtDate[button.tag];
[self LoadClasses];
[btnCurrentSelected setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal] // set color for old button selected
btnCurrentSelected = button
[btnCurrentSelected setTitleColor:[UIColor blueColor] forState:UIControlStateNormal] // set color for button selected
__weak typeof(self) weakSelf = self;
[weakSelf updateCurrentPageIndex:button.tag];
NSInteger xCoor = selectionBar.frame.size.width*self.currentPageIndex;
selectionBar.frame = CGRectMake(xCoor, selectionBar.frame.origin.y, selectionBar.frame.size.width, selectionBar.frame.size.height);
}
You don't need to use UIButton here, just need to customize a UIControl subclass where the needed customize layout inside, you need to handle highlighting Or general state inside the selected Set method
I tried to create UIDatePicker without storyboard and let the UILabel of the selected date show, but the label is shown like its being piled up when another date is picked on simulator.
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10,100,100)];
[self.view addSubview:myLabel];
UIDatePicker *myPicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
myPicker.datePickerMode = UIDatePickerModeDate;
[myPicker addTarget:self action:#selector(pickerChanged:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:myPicker];
}
- (void)pickerChanged:(id)sender
{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 300, 200, 200)];
df.dateFormat = #"yyyy/MM/dd HH:mm";
myLabel.text = [df stringFromDate:[sender date]];
[self.view addSubview:myLabel];
}
The screenshot is as follows:
http://i.stack.imgur.com/VnJbD.png
I am a beginner and couldn't find the solution. Can somebody know how to solve this problem? Thank you in advance.
This is because you are creating a new label every time the date change
You need to reuse your component, create it in view did load
- (void)viewDidLoad() {
....
self.myLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 300, 200, 200)];
[self.view addSubview:self.myLabel];
}
So then you can just set the text:
- (void)pickerChanged:(id)sender {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateFormat = #"yyyy/MM/dd HH:mm";
self.myLabel.text = [df stringFromDate:[sender date]];
}
First add Label in viewDidLoad
UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 300, 200, 200)];
[self.view addSubview:self.myLabel];
and then add date in your Label in PickerChange
self.myLabel.text = [df stringFromDate:[sender date]];
I have following three UITextfields associated with UIDatePickers.
self.taskDate.inputView=[self returnDatePickerView:01];
self.taskStartTime.inputView=[self returnDatePickerView:02];
self.taskEndtime.inputView=[self returnDatePickerView:03];
This is my DatePicker method
- (UIView *)returnDatePickerView:(int)tag{
UIToolbar *toolBar1 = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
toolBar1.barStyle = UIBarStyleBlackTranslucent;
UIBarButtonItem *doneButton3 = [[UIBarButtonItem alloc] initWithTitle:#"Done"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(taskDateDone)];
[toolBar1 setItems:[NSArray arrayWithObjects:doneButton3, nil]];
UIView *dateView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 200)];
datePicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
if(tag==01){
datePicker.datePickerMode=UIDatePickerModeDate;
}else{
datePicker.datePickerMode=UIDatePickerModeTime;
}
//Setting user selected date as the date picker default
[datePicker setDate:taskDate animated:YES];
[datePicker addTarget:self action:#selector(taskDatePicked:)forControlEvents:UIControlEventValueChanged];
[dateView addSubview:datePicker];
[dateView addSubview:toolBar1];
return dateView;
}
Here is my call back taskDatePicked
- (void)taskDatePicked:(id)sender
{
NSDateFormatter *systemtimeFormatter = [[NSDateFormatter alloc] init];
NSLog(#"tag %ld",textFieldTag);
//[systemtimeFormatter setTimeZone:[NSTimeZone systemTimeZone]];
if(textFieldTag==01){
taskDate = datePicker.date;
[systemtimeFormatter setDateStyle:NSDateFormatterShortStyle];
self.taskDate.text=[[NSString alloc] initWithString:[systemtimeFormatter stringFromDate:taskDate]];
}else if(textFieldTag==02){
taskStartTime = datePicker.date;
[systemtimeFormatter setTimeStyle:NSDateFormatterShortStyle];
self.taskStartTime.text=[[NSString alloc] initWithString:[systemtimeFormatter stringFromDate:taskStartTime]];
NSLog(#"taskStartTime picked date %#",taskStartTime.description);
}else if(textFieldTag==03){
taskEndTime = datePicker.date;
[systemtimeFormatter setTimeStyle:NSDateFormatterShortStyle];
self.taskEndtime.text=[[NSString alloc] initWithString:[systemtimeFormatter stringFromDate:taskEndTime]];
}
[datePicker reloadInputViews];
}
But this method is not calling for all UITextfieds.
What i did wrong here. Please suggest
Try the following code for using single date picker as input view for multiple text fields with different date/time formats.
Here input views for the text fields are assigned in the text field delegate.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
Consider UIDatePicker *datePicker; is the common date picker and NSInteger textFieldTag; holds the tag of the current text field (Both added in the interface extention).
Make sure tag value is assigned for the text fields and delegate is connected for each fields.Then add the following in the viewDidLoad method.
datePicker = [[UIDatePicker alloc] init];
[datePicker addTarget:self action:#selector(taskDatePicked:) forControlEvents:UIControlEventValueChanged];
Add the text field delegate like :
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
switch (textField.tag)
{
case 1:
datePicker.datePickerMode = UIDatePickerModeDate;
break;
case 2:
datePicker.datePickerMode = UIDatePickerModeTime;
break;
case 3:
datePicker.datePickerMode = UIDatePickerModeTime;
break;
default:
break;
}
textField.inputView = datePicker;
textFieldTag = textField.tag;
return YES;
}
And the event triggered with the date picker changes is as follows:
- (void)taskDatePicked:(id)sender
{
UITextField *textField = (UITextField *)[self.view viewWithTag:textFieldTag];
NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
dateformatter.dateStyle = NSDateFormatterMediumStyle;
switch (textFieldTag)
{
case 1:
[dateformatter setDateFormat:#"dd-MM-YYYY"];
break;
case 2:
[dateformatter setDateFormat:#"hh:mm a"];
break;
case 3:
[dateformatter setDateFormat:#"hh:mm a"];
break;
default:
break;
}
textField.text = [dateformatter stringFromDate:[datePicker date]];
}
Please set the tag value to textFieldTag
- (UIView *)returnDatePickerView:(int)tag{
UIToolbar *toolBar1 = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
toolBar1.barStyle = UIBarStyleBlackTranslucent;
UIBarButtonItem *doneButton3 = [[UIBarButtonItem alloc] initWithTitle:#"Done"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(taskDateDone)];
[toolBar1 setItems:[NSArray arrayWithObjects:doneButton3, nil]];
UIView *dateView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 200)];
datePicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
if(tag==01){
datePicker.datePickerMode=UIDatePickerModeDate;
}else{
datePicker.datePickerMode=UIDatePickerModeTime;
}
//Setting user selected date as the date picker default
[datePicker setDate:taskDate animated:YES];
[datePicker addTarget:self action:#selector(taskDatePicked:)forControlEvents:UIControlEventValueChanged];
textFieldTag = tag;
[dateView addSubview:datePicker];
[dateView addSubview:toolBar1];
return dateView;
}
I have a UITextField that I set the inputView to a UIDatePicker so that when the UITextField is pressed, instead of a keyboard, a UIDatePicker pops up. I would like to also add a toolbar with a 'Next' button on it so that the user could easily jump to the next field, but I am not sure how to do this as I am already altering a view on the UITextField to get the UIDatePicker. Here is the code used in loading the view:
- (void)viewDidLoad
{
self.datePicker = [[UIDatePicker alloc] init];
self.datePicker.datePickerMode = UIDatePickerModeDate;
[self.datePicker addTarget:self action:#selector(datePickerValueChanged) forControlEvents:UIControlEventValueChanged];
issue.inputView = self.datePicker;
}
Suggestions for getting the 'Next' button added to a toolbar on top of it?
Create a view to use as the text field's inputAccessoryView. This view should contain your buttons (e.g. Next, Cancel, Previous).
Here's the code :
if (keyboardToolbar == nil) {
keyboardToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
[keyboardToolbar setBarStyle:UIBarStyleBlackTranslucent];
UIBarButtonItem *extraSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *next = [[UIBarButtonItem alloc] initWithTitle:#"Next" style:UIBarButtonItemStyleDone target:self action:#selector(switchToNextField:)];
[keyboardToolbar setItems:[[NSArray alloc] initWithObjects: extraSpace, next, nil]];
}
issue.inputAccessoryView = keyboardToolbar;
datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:#selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
issue.inputView = datePicker;
And in your switchToNextField method, just make the nextField as the firstResponder using [nextTextField becomeFirstResponder];
You can create a view then put any UI elements inside of it.
#property (nonatomic,strong) UIPopoverController *popoverControllerBirthday;
add above to your .h file and sync it at .m #synthesize popoverControllerBirthday;
also change your #synthesize datePicker; to #synthesize datePicker=_datePicker;
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
if (textField==self.yourtextfield) {
UIViewController* popoverContent = [[UIViewController alloc] init]; //ViewController
UIView *popoverView = [[UIView alloc] init]; //view
popoverView.backgroundColor = [UIColor blackColor];
_datePicker=[[UIDatePicker alloc]init];//Date picker
_datePicker.frame=CGRectMake(0,0,320, 216);
_datePicker.datePickerMode = UIDatePickerModeDate;
[_datePicker setMinuteInterval:5];
[_datePicker setTag:10];
[popoverView addSubview:_datePicker];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(result)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"Next" forState:UIControlStateNormal];
button.frame = CGRectMake(0, 220, 320, 45);
UIColor *titleColor = [UIColor whiteColor];
[button setTitleColor:titleColor forState:UIControlStateNormal];
// UIImage *doneButtonImage = [UIImage imageNamed:#"create event button.png"]; choose a button background if you ahve one
[button setBackgroundImage:doneButtonImage forState:UIControlStateNormal];
[popoverView addSubview:button];
popoverContent.view = popoverView;
popoverControllerBirthday = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
popoverControllerBirthday.delegate=self;
CGRect myFrame =textField.frame;
myFrame.origin.x = 200;// your coordinates change it as you wish
myFrame.origin.y = 195;
[popoverControllerBirthday setPopoverContentSize:CGSizeMake(320, 265) animated:NO];
[popoverControllerBirthday presentPopoverFromRect:myFrame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
return NO; // tells the textfield not to start its own editing process (ie show the keyboard)
}
else{
return YES;
}
}
//handle your result call next uitextfield in your case
-(void) result
{
//in result method you can get date using datepicker.date
if (self.popoverControllerBirthday)
{
[self.popoverControllerBirthday dismissPopoverAnimated:NO];
self.popoverControllerBirthday = nil;
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateFormat:#"M d yyyy"];
NSString *parseDatePickerDAte =[dateFormatter stringFromDate:_datePicker.date]; // your string that is choosen at datepicker
// self.textfield.text = parseDatePickerDAte ; set this to your textfield if you want
//google this dont remember exact code for that, just changing your textfield to desired one
[self.nexttextfield becomesFirstResponder];
}
You can use SMDatePicker instead of UIDatePicker. It will create a custom view with UIToolbar and UIDatePicker. You can easy customise toolbar with necessary buttons. Take a look at example project.
I am fairly new to iOS programming so this might be a really simple mistake. Anyways, I have a subview which I want to appear on top of a "normal" view such that a user can input a date with a UIDatePicker and confirm his choice with a UIBarButtonItem (which will also prompt the subview to disappear) in a UIToolbar. The problem is that the control elements (Picker and Button) dont respond to tapping and other gestures despite being visible on top of the "normal" view. I noticed that a button which is part of the "normal" view responds instead, even though, this button lies beneath the subview and is not visible. Here is the code which generates the subview with its elements:
UIView * newView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 0)];
newView.backgroundColor = [UIColor colorWithWhite:1 alpha:1];
UIToolbar * toolbar = [[UIToolbar alloc] initWithFrame: CGRectMake(0, 0, 320, 49)];
toolbar.barStyle = UIBarStyleBlack;
UIBarButtonItem *infoButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Done" style:UIBarButtonItemStyleDone target:nil action:#selector(dismissCustom:)];
toolbar.items = [NSArray arrayWithObjects:infoButtonItem, nil];
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.hidden = NO;
datePicker.date = [NSDate date];
datePicker.frame = CGRectMake(0, 49, 320, 250);
datePicker.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[datePicker addTarget:self action:#selector(pickerDateChanged:) forControlEvents:UIControlEventValueChanged];
[newView addSubview:datePicker];
[newView addSubview:toolbar];
[self.view addSubview:newView];
[self.view bringSubviewToFront:newView];
newView.tag = 1;
The methods dismissCustom: and pickerDateChanged: are as follows:
-(void)pickerDateChanged:(UIDatePicker *)sender
{
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSLog(#"Picked the date %#", [dateFormatter stringFromDate:[sender date]]);
dateButton.titleLabel.text = [dateFormatter stringFromDate:sender.date];
}
and
-(void)dismissCustom:(UIBarButtonItem *)sender
{
UIView * newView = [[UIView alloc] viewWithTag:1];
[newView removeFromSuperview];
}
Does anybody have an idea what is missing / wrong? Any help is appreciated!
Cheers
At least for the button, you need to add a touchUpInside event for the action:
[button addTarget:self action:#selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];