iOS開發日記48-詳解UIPickerView,48-uipickerview
今天博主有一個UIPickerView的需求,遇到了一些困痛點,在此和大家分享,希望能夠共同進步.
UIPickerView是一個選取器控制項,它比UIDatePicker更加通用,它可以產生單列的選取器,也可產生多列的選取器,而且開發人員完全可以自訂選擇項的外觀,因此用法非常靈活.
UIPickerView直接繼承了UIView,沒有繼承UIControl,因此,它不能像UIControl那樣綁定事件處理方法,UIPickerView的事件處理由其委派物件完成.
self.viewOfPick=[[UIPickerView alloc]initWithFrame:CGRectMake(100, 0, 200, [UIScreen mainScreen].bounds.size.height)];
_viewOfPick.dataSource=self;
_viewOfPick.delegate=self;
//pickerView預設選中row為0,無線滾動只是在一開始的時候顯示row的中間值,造成無線滾動的假象
[_viewOfPick selectRow:9 inComponent:0 animated:YES];
//設定pickerView預設選中最後一行
[_viewOfPick selectRow:9 inComponent:1 animated:YES];
[self.view addSubview:_viewOfPick];
//類似tableView的cell for row,根據row和component返回字串顯示
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component __TVOS_PROHIBITED
{
return @"空";
}
//類似tableView的didSelect,根據row和component進行具體的傳值等操作
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component __TVOS_PROHIBITED
{
NSLog(@"*********%ld,%ld",(long)component,row);
}
//類似tableView的cell for row,根據row和component返回自訂視圖顯示
//注意,同時實現返回NSString 和下面這個 返回UIView的方法,只執行返回UIView的方法
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view __TVOS_PROHIBITED
{
UIView *blackView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 10)];
blackView.backgroundColor=[UIColor blackColor];
return blackView;
}
//返回pickerView的行高
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component __TVOS_PROHIBITED
{
return 40;
}
// returns the number of 'columns' to display.component的數量
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
// returns the # of rows in each component..row的數量
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return 10;
}