我正在尝试实施日历。我有一个年份标签和两个按钮,用于递增和递减日历年份。我得到这个异常(Thread1:EXC_BAD_ACCESS(代码= 1,地址= 0x5146a345)),而点击按钮(增加或减少)我的要求是,如果我点击右键我的年份应该增加,如果我点击左按钮我的一年应该减少。我的例外行date = [cal dateByAddingUnit:NSCalendarUnitYear value:1 toDate:date options:0];
可以帮助您解决此问题。这是我的代码
- (void)viewDidLoad
{
[super viewDidLoad];
date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY"];
NSString *stringFromDate = [formatter stringFromDate:date];
yar1.text=stringFromDate;
}
- (IBAction)right:(id)sender {
NSCalendar *cal = [NSCalendar currentCalendar];
date = [cal dateByAddingUnit:NSCalendarUnitYear value:1 toDate:date options:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY"];
NSString *stringFromDate = [formatter stringFromDate:date];
yar1.text=stringFromDate;
}
- (IBAction)left:(id)sender {
NSCalendar *cal = [NSCalendar currentCalendar];
date = [cal dateByAddingUnit:NSCalendarUnitYear value:1 toDate:date options:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY"];
NSString *stringFromDate = [formatter stringFromDate:date];
yar1.text=stringFromDate;
}
答案 0 :(得分:0)
您需要一个日期组件来更改日期,
-(NSDate *)offsetYear:(int)numOfYears date:(NSDate*)date
{
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setYear:numOfYears];
return [[NSCalendar currentCalendar] dateByAddingComponents:offsetComponents
toDate:date options:0]; }
将偏移量传递为1表示右侧,-1表示左侧