我在使用storyboard的视图上有一个UISegmentedControl
,目前正在使用以下代码行编写文本:
[segMonth setTitle:@"Month 1" forSegmentAtIndex:0];
[segMonth setTitle:@"Month 2" forSegmentAtIndex:1];
我还有一个使用此代码的日期函数,它获取当前月份的数字(1-12):
// Date
NSDate *now = [NSDate date];
NSString *strDate = [[NSString alloc] initWithFormat:@"%@",now];
NSArray *arr = [strDate componentsSeparatedByString:@" "];
NSString *str;
str = [arr objectAtIndex:0];
NSArray *arr_my = [str componentsSeparatedByString:@"-"];
NSInteger month = [[arr_my objectAtIndex:1] intValue];
//End Date
我试图将当前月份“12月”的第一段命名为下一个月“1月份”的第二段。
我尝试使用以下代码,但它似乎不起作用:
[segMonth setTitle:@"%d" forSegmentAtIndex:0];
[segMonth setTitle:@"%d" forSegmentAtIndex:1];
显然,这也只会给出月份的数量,而不是名称..
答案 0 :(得分:1)
您传入字符串格式化程序并期望它包含月份的名称。尝试
[segMonth setTitle:[NSString stringWithFormat:@"%@",str1] forSegmentAtIndex:0];
[segMonth setTitle:[NSString stringWithFormat:@"%@",str2] forSegmentAtIndex:1];
str1和str2应该是包含月份名称的字符串(可通过NSDateFormatter获得)。
答案 1 :(得分:1)
从这样的数字中获取月份名称:
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
NSString *monthName = [[df monthSymbols] objectAtIndex:(yourMonthNumberHere-1)];
现在使用它:
[segMonth setTitle:monthName forSegmentAtIndex:0];
答案 2 :(得分:1)
我已经看到了你的代码,其中包含了从NSDate
获得一个月的非常困难的方法。我知道,这可能不是答案。但我只是要求您检查此代码,以了解获取月份,日期或时间或与NSDate
分开的任何内容的正确方法。
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSMonthCalendarUnit fromDate:today];
NSInteger currentMonth = [components month]; // this will give you the integer for the month number
[components setMonth:1];
NSDate *newDate = [gregorian dateByAddingComponents:components toDate:today options:0];
NSDateComponents *nextComponents = [gregorian components:NSMonthCalendarUnit fromDate:newDate];
<强>更新:强>
NSInteger nextMonth = [nextComponents month]; // this will give you the integer for the month number
并且@Prince说你可以从NSDateFormatter
获得月份名称。无论如何,我重复一遍让你明白。
NSDateFormatter *df = [[NSDateFormatter alloc] init];
NSString *currentMonthName = [[df monthSymbols] objectAtIndex:(currentMonth-1)];
NSString *nextMonthName = [[df monthSymbols] objectAtIndex:(nextMonth-1)];
[segMonth setTitle:currentMonthName forSegmentAtIndex:0];
[segMonth setTitle:nextMonthName forSegmentAtIndex:1];
答案 3 :(得分:0)
int currentMonth = 12; //December
int nextMonth = 1; //January
NSDateFormatter *df1 = [[[NSDateFormatter alloc] init] autorelease];
NSString *currentMonthName = [[df1 monthSymbols] objectAtIndex:(currentMonth-1)];
NSDateFormatter *df2 = [[[NSDateFormatter alloc] init] autorelease];
NSString *nextMonthName = [[df2 monthSymbols] objectAtIndex:(nextMonth-1)];
[segMonth setTitle:currentMonthName forSegmentAtIndex:0];
[segMonth setTitle:nextMonthName forSegmentAtIndex:1];
请注意,您需要从currentMonth和nextMonth(从1到12)中减去1,因为monthSymbols从零开始。