将UIButton的文本设置为日期

时间:2011-04-14 06:18:12

标签: iphone objective-c

我有一个UIButton,当点击时会显示一个UIDatePicker来设置它的日期。

所有内容都设置了动画进出等等。

我需要帮助:

默认情况下,将按钮的文本标签设置为日期。然后在UIDatePicker被解除后将其设置为新选择的日期。

 - (IBAction)dateButtonPressed
{
    [dateView setFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height)];
    [self.view addSubview:dateView];

    [UIView animateWithDuration:.5 animations:^{
        [dateView setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    }];
}

- (IBAction)dismssPicker
{
    [dateView setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

    [UIView animateWithDuration:.5 animations:^{
        [dateView setFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height)];
    } completion:^(BOOL finished){ [dateView removeFromSuperview]; }];
}

3 个答案:

答案 0 :(得分:1)

你可能想要这样的东西:

[button setTitle:[[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d"
                                    timezone:nil
                                      locale:nil] forState:UIControlStateNormal];

答案 1 :(得分:1)

- (void)setTitle:(NSString *)title forState:(UIControlState)state

更改按钮的文字。

喜欢

[button setTitle:[date description] forState:UIControlStateNormal]

答案 2 :(得分:0)

首先改变你的方法。 (我假设您已将此连接到UIDatePicker)

 -(IBAction)dismssPicker:(UIDatePicker*)datePicker
{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    NSDate *date = datePicker.date;
    [dateFormatter setDateFormat:@"MMM dd, yyyy"]; 
    NSString *dateString = [dateFormatter stringFromDate:date]; 
//set it now


    [dateView setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

    [UIView animateWithDuration:.5 animations:^{
        [dateView setFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height)];
    } completion:^(BOOL finished){ [dateView removeFromSuperview]; }];
}

对于您的下一个问题,请在.h文件中填写NSDate *prvDate;

-(IBAction)changeDate:(id)sender{
    prvDate = yourCurrentDate;  //save your previous date 
    yourCurrentDate = datePicker.date;
//set the button's label here
}

 -(IBAction)cancel:(id)sender{
    yourCurrentDate = prvDate;
//set the button's label here
}