gpt4 book ai didi

ios - 单击下一个和上一个UIButton时在UILabel中更改日期

转载 作者:行者123 更新时间:2023-12-01 17:25:08 26 4
gpt4 key购买 nike

UILabel中设置一个日期。
单击“下一个”和“上一个”按钮应更改此标签内的日期。

我正在尝试此代码,但是单击下一个按钮并显示日期第二天日期为例如01/05/2015和上一个按钮单击并设置日期为29/05/2015,下一个按钮单击则不显示02/05/2015

- (IBAction)changeToNextDay:(id)sender
{
NSDateComponents* deltaComps = [[NSDateComponents alloc] init];
[deltaComps setDay:+1];
NSDate* tomorrow = [[NSCalendar currentCalendar] dateByAddingComponents:deltaComps toDate:[NSDate date] options:0];

NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setDateFormat:@"dd-MM-yyyy"];

NSString *stringFromDate = [myDateFormatter stringFromDate:tomorrow];
dateLabel.text = stringFromDate;
}

- (IBAction)changeToPreviousDay:(id)sender
{
NSDate *datePlusOneDay = [[NSDate date] dateByAddingTimeInterval:-(60 * 60 * 24)];
NSLog(@"datePlusOneDay=%@",datePlusOneDay);

NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setDateFormat:@"dd-MM-yyyy"];

NSString *stringFromDate = [myDateFormatter stringFromDate:datePlusOneDay];
dateLabel.text = stringFromDate;
}

最佳答案

- (void)viewDidLoad {
[super viewDidLoad];
[self Update_Date_By:0];
}

- (IBAction)changeToNextDay:(id)sender {
[self Update_Date_By:1];
}

- (IBAction)changeToPreviousDay:(id)sender {
[self Update_Date_By:-1];
}

-(void)Update_Date_By:(NSInteger)value {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/yyyy"];
NSDate *date = [dateFormat dateFromString:dateLabel.text];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [NSDateComponents new];
dateComponents.day = value;
if (value == 0) {
date = [NSDate date];
}
NSDate *newDate = [calendar dateByAddingComponents:dateComponents toDate:date options:0];
[dateFormat setDateFormat:@"dd/MM/yyyy"];
NSString *finalDate_String = [dateFormat stringFromDate:newDate];
dateLabel.text = finalDate_String;
}

关于ios - 单击下一个和上一个UIButton时在UILabel中更改日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29967503/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com