如何使用datepicker在按钮上显示所选日期?

时间:2012-08-29 11:50:32

标签: iphone ios ios4 ios5.1

当我点击我的按钮时,我能够成功地显示日期选择器。但是当我从日期选择器中选择日期时,我无法在UIbutton上显示所选日期。请帮助我

这是我的代码:

-(IBAction)btnDateClicked:(id)sender
{ 
UIActionSheet *actionSheet1 = [[UIActionSheet alloc] initWithTitle:nil 
                                                          delegate:nil
                                                 cancelButtonTitle:nil
                                            destructiveButtonTitle:nil
                                                 otherButtonTitles:nil];

[actionSheet1 setActionSheetStyle:UIActionSheetStyleBlackTranslucent];

CGRect pickerFrame = CGRectMake(0, 40, 0, 0);


UIDatePicker *pView=[[UIDatePicker alloc] initWithFrame:pickerFrame];

pView.datePickerMode=UIDatePickerModeDate; 

NSDateFormatter *df=[[NSDateFormatter alloc] init];

[df setDateFormat:@"MM/dd/yyyy"];

// NSDate *date=[df dateFromString:self.hController.fromDateTime];

// [pView setDate:date animated:YES];

self.datePicker=pView;

[actionSheet1 addSubview:self.datePicker];

[pView release];

UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Done"]];

closeButton.momentary = YES; 

closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);

closeButton.segmentedControlStyle = UISegmentedControlStyleBar;

closeButton.tintColor = [UIColor blackColor];

[closeButton addTarget:self action:@selector(dismissActionSheet1:) forControlEvents:UIControlEventValueChanged];

[actionSheet1 addSubview:closeButton];

[closeButton release];

[actionSheet1 showInView:[[UIApplication sharedApplication] keyWindow]];

[actionSheet1 setBounds:CGRectMake(0, 0, 320, 485)];

self.actionSheet=actionSheet1;

[actionSheet1 release];
}
///////////////////////////////////
- (void)dismissActionSheet1:(id)sender
{
[self.actionSheet dismissWithClickedButtonIndex:0 animated:YES];

NSDateFormatter *df=[[NSDateFormatter alloc] init];

[df setDateFormat:@"MM/dd/yyyy"];   

//NSString *str=[df stringFromDate:self.datePicker.date]; 

//self.hController.selectDate=str;    
}

4 个答案:

答案 0 :(得分:1)

将一些标签作为子视图添加到显示其点击事件选择器视图的按钮。从日期选择器中选择日期将标签文本更新为所选日期

答案 1 :(得分:1)

你必须使用UIPickerViewDataSource,UIPickerViewDelegate方法。创建一个日期数组你在pickerView中显示并使用以下方法。

- (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component 
{

[ closeButton setTitle:[NSString StringWithFormat:@"%@",[datesArray objectAtIndex:row]] forState:UIControlStateNormal];
}

答案 2 :(得分:0)

使用此按钮更新按钮上的标题

[ closeButton setTitle:str forState:UIControlStateNormal];

答案 3 :(得分:0)

使用IBOutlet连接按钮然后在下面的方法中使用

设置按钮的文本
  - (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component
     {
        [ closeButton setTitle:[NSString StringWithFormat:@"%@",[datesArray objectAtIndex:row]]  forState:UIControlStateNormal];

     }

你完成了:)