一、概述
iOS UIPickerView是一種數據選擇器控件,可以讓用戶通過滑動選擇一系列數據。它通常用於創建表單、選項卡、菜單等用戶輸入界面。
使用UIPickerView可以使用戶在獲得信息時更加方便,同時也可以提高應用的可用性和友好性。
二、UIPickerView的使用
1、創建UIPickerView
UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 320, 216)]; pickerView.delegate = self; pickerView.dataSource = self; [self.view addSubview:pickerView];
需要注意的是,我們要實現UIPickerViewDataSource和UIPickerViewDelegate兩個協議,才能為UIPickerView提供數據和顯示。
2、實現UIPickerViewDataSource協議
numberOfComponentsInPickerView
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return 3; }
此方法返回UIPickerView中包含的“列數”,也就是有幾個數據集合需要操作。例如日期、時間需要操作年/月/日,或者一個選擇器里需要選擇同時需要姓名、年齡、性別。
numberOfRowsInComponent
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { return self.dataArray.count; }
此方法返回每一列需要展示的數據數量。需要注意,這裡返回的數量應該跟數據源中對應列的數據集合數量一致,否則會出現程序崩潰。
3、實現UIPickerViewDelegate協議
viewForRow
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view { UILabel *titleLabel = [[UILabel alloc] init]; [titleLabel setText:[self.dataArray objectAtIndex:row]]; return titleLabel; }
此方法返回每一列上的每一個行的view視圖,也就是顯示在picker中每一行上自定義的視圖。在此方法中,我們通常會利用常見的UIKit控件來自定義view對象。
didSelectRow
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { NSLog(@"你選擇的是%ld列中的%ld行", component, row); }
此方法是當行被選擇後的回調,返回選中的行及所屬的列。這裡可以利用該方法來處理行選擇器中的數據內容。
三、樣式定製
設置每行顯示內容的字體大小和字體顏色
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view { UILabel *titleLabel = [[UILabel alloc] init]; [titleLabel setText:[self.dataArray objectAtIndex:row]]; [titleLabel setTextAlignment:NSTextAlignmentCenter]; [titleLabel setFont:[UIFont systemFontOfSize:16]]; [titleLabel setTextColor:[UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1]]; return titleLabel; }
設置分割線顏色
pickerView.separatorColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];
設置每行的高度
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component { return 40.0f; }
設置每行的寬度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component { return 80; }
四、小結
本文詳細的介紹了iOS UIPickerView的使用,從創建UIPickerView到實現UIPickerViewDataSource、UIPickerViewDelegate兩個協議的方法,再到樣式定製等相關知識點的講解,基本能夠幫助理解和快速上手。在應用的開發過程中,合理使用UIPickerView能夠使用戶使用體驗得到很大的提升。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/194242.html