UIDatePicker select Month and Year

前端 未结 11 1869
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 04:00

I need a UIDatePicker for selecting Month and Year only. I checked the class reference documents. Looks like UIDatePicker is a UIView.

11条回答
  •  执笔经年
    2020-11-27 04:23

    I'm using a simple UIPickerView with 2 components (months and years).

    And calling the UIPickerViewDelegate with every row selection:

    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
    {
        //Today year and month
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"yyyy"];
        int year = [[dateFormat stringFromDate:[NSDate date]] intValue];
        [dateFormat setDateFormat:@"MM"];
        int month = [[dateFormat stringFromDate:[NSDate date]] intValue] - 1;
    
        //picker year and month
        int selectedYear = [[self.yearsArray objectAtIndex:[pickerView selectedRowInComponent:1]] intValue];
        int selectedMonth = [pickerView selectedRowInComponent:0];
    
        // if month in the past, change the month
        if (year == selectedYear && selectedMonth < month)
        {
            [pickerView selectRow:month inComponent:0 animated:YES];
        }
    }
    

提交回复
热议问题