Xcode Saving UIDatepicker to be displayed in a label

寵の児 提交于 2019-12-06 14:11:57

.h

#import <UIKit/UIKit.h>
@interface YourViewController : UIViewController {
    IBOutlet UILabel *label1;
}
@property (nonatomic, retain) UILabel *label1;
@end

.m

@implementation YourViewController
@synthesize label1;
/*
     All of your code goes here
 */
@end

Interface Builder


Also add the following to your showActionSheet:

[datePicker addTarget:self
               action:@selector(updateLabel:)
     forControlEvents:UIControlEventValueChanged];

This should update your label from datePicker:

-(void)updateLabel:(id)sender
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateStyle = NSDateFormatterMediumStyle;
    label1.text = [NSString stringWithFormat:@"%@",[df stringFromDate:datePicker.date]];
    [df release];


    /* the following allows you to choose the date components
    NSCalendar *calendar = [NSCalendar currentCalendar];

    int hour   =    [[calendar components:NSHourCalendarUnit    fromDate:[datePicker date]] hour];
    int minute =    [[calendar components:NSMinuteCalendarUnit  fromDate:[datePicker date]] minute];

    int year   =    [[calendar components:NSYearCalendarUnit    fromDate:[datePicker date]] year];
    int month  =    [[calendar components:NSMonthCalendarUnit   fromDate:[datePicker date]] month];
    int day    =    [[calendar components:NSDayCalendarUnit     fromDate:[datePicker date]] day];
      */
}

Here I shows that UIDatePicker in UITableview cell. I hope it would help.

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {   
    // Make a new view, or do what you want here    
    UIDatePicker *pv = [[UIDatePicker alloc] initWithFrame:CGRectMake(0,185,0,0)];    
    [self.view addSubview:pv];    
    return NO;    
}

If you are using UITableView, then use following in order to show UIDatePicker instead of keyboard.

if (0 == indexPath.row) {
    cell.rightTextField.placeholder = @”Date”;
    cell.rightTextField.text = [coAccident strDateTime];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

UIDatePicker *datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, 185, 0)];
[datePicker addTarget:self action:@selector(changeDateInLabel :) forControlEvents:UIControlEventValueChanged];
cell.rightTextField.inputView = datePicker;
} 

- (IBAction)changeDateInLabel:(id)sender {
    UIDatePicker * datePicker = (UIDatePicker*)sender;
    CAccidentVO* coAccident = [m_arrVehicles objectAtIndex:1];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateStyle = NSDateFormatterMediumStyle;   
    [coAccident setStrDateTime:[NSString stringWithFormat:@"%@",[df stringFromDate:datePicker.date]]];  
    [df release];  
    [m_tvVehicleDetails reloadData];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!