刚开始学习Obj-C;原谅天真的问题,如果有的话。
我正在尝试根据在datepicker中选择的日期创建一个显示自定义alertview的应用程序。
这是我现在的代码,当选择任何日期并点击按钮时,它会显示硬编码的警报视图。如何依赖所选日期。
(#)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
答案 0 :(得分: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”。
答案 1 :(得分:0)
您需要一个数据结构,最好是一个字典,其中键是日期,值是您要在警报中显示的字符串。在日期选择器中选择日期后,在字典中搜索与该日期匹配的键,并在警报视图中将该键的值分配给该消息。