首页 > 代码库 > UIDatePicker和UIPickerView的使用

UIDatePicker和UIPickerView的使用

 UIDatePicker *datePicker = [ [ UIDatePicker alloc] initWithFrame:CGRectMake(0,0,320,216)];

    datePicker.datePickerMode = UIDatePickerModeDateAndTime;

    datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];

    [datePicker addTarget:self action:@selector(dateChange:) forControlEvents:UIControlEventValueChanged];

    [self.view addSubview:datePicker];

 

- (void)dateChange:(UIDatePicker *)datePicker

{
    NSDate *theDate = datePicker.date;
    NSLog(@"%@",[theDate descriptionWithLocale:[NSLocale currentLocale]]);
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"YYYY-MM-dd HH-mm-ss";
    NSLog(@"%@",[dateFormatter stringFromDate:theDate]);
}

运行效果:

                               技术分享

UIPickerView的使用:

#define currentView_Center CGPointMake([UIScreen mainScreen].bounds.size.width * 1.0 / 2, [UIScreen mainScreen].bounds.size.height * 1.0 / 2)

    UIPickerView *pickView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 100)];

    pickView.delegate = self;

    pickView.dataSource = self;

    [pickView setShowsSelectionIndicator:YES];

    pickView.center = currentView_Center;

    [self.view addSubview:pickView];

    self.area = @[@"刘国梁",@"孔令辉"];

    self.area = [self.area sortedArrayUsingSelector:@selector(compare:)];

    self.dataSourceArr = @[@"王皓",@"马琳",@"王励勤",@"张继科",@"马龙",@"许昕",@"樊振东",@"周雨",@"尚坤",@"波尔"];

    self.dataSourceArrM = @[@"丁宁",@"刘诗雯",@"李晓霞",@"陈梦",@"武杨",@"郭跃"];

    self.picKViewDic = @{self.area[0]:self.dataSourceArr, self.area[1]:self.dataSourceArrM};

    self.selectedArea = self.area[0];

#pragma mark - UIPickerViewDataSource

 

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {

    return 2;

}

 

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {

    if (component == 0) {

        return self.area.count;

    }

    return [self.picKViewDic[_selectedArea] count];

}

 

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {

    if (component == 0) {

        return self.area[row];

    }

    return self.picKViewDic[_selectedArea][row];

}

 

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    if (component == 0) {

        _selectedArea = self.area[row];

        [pickerView reloadComponent:1];

        [pickerView selectRow:0 inComponent:1 animated:YES];

    

    }

}

 

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {

    if (component == 0) {

        return 100;

    }

    return 220;

UIDatePicker和UIPickerView的使用