0

刚开始学习Obj-C;如果有天真的问题,请原谅。

我正在尝试创建一个应用程序,该应用程序根据在日期选择器中选择的日期显示自定义警报视图。

This is the code i have right now that shows a hard-coded alertview when any date is selected and the button is tapped. 我怎样才能使依赖于所选日期。

(#)import "APViewController.h"
@interface APViewController ()
@end

@implementation APViewController
@synthesize datePicker;

- (void)viewDidLoad
{
[super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (IBAction)specialButton:(id)sender {

//  NSDate *chosen = [datePicker date];

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Woohoo !" message:@"Its your   50th Birthday" delegate:nil cancelButtonTitle:@"Thanks" otherButtonTitles:nil];

[alert show];

}

@end    
4

2 回答 2

0

您需要一个数据结构,最好是一个字典,其中键是日期,值是要在警报中显示的字符串。在日期选择器中选择日期后,在字典中搜索与该日期匹配的键,并将该键的值分配给警报视图中的消息。

于 2013-07-26T04:34:50.573 回答
0

使用 NSDateFormatter 将日期选择器的日期格式化为您想要的格式,然后在警报中显示:

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"cccc, MMM d, hh:mm aa"];
NSString * dateString = [dateFormatter stringFromDate:datePicker.date];

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Woohoo !" message:dateString delegate:nil cancelButtonTitle:@"Thanks" otherButtonTitles:nil];

[alert show];

如果您试图显示用户的年龄,假设他们将日期选择器放在他们的生日上,请使用 NSDateComponents 获取日期的年份以及当前年份。

NSDateComponents * currentDateComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:[NSDate date]];
NSDateComponents * pickedDateComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:datePicker.date];

NSInteger diff = currentDateComponents.year - pickedDateComponents.year;

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Woohoo !" message:[NSString stringWithFormat:@"Its your %dth Birthday", diff] delegate:nil cancelButtonTitle:@"Thanks" otherButtonTitles:nil];

[alert show];

您必须确保它并不总是“th”。它可以是“st”或“nd”或“rd”。

于 2013-07-25T23:50:03.257 回答