標籤:style blog http 使用 strong io 檔案 資料
UITableView.02:
【1】拖入一個UITableView
【2】將TableView的dataSource與控制器串連
【3】首先得遵循UITableView的資料來源協議<UITableViewDataSource>
【4】將資料plist檔案拖入
【5】代碼
1.viewDidLoad只載入一次,所以用來載入plist檔案中的資料。
建立一個bundel用來指定檔案路徑
pathForResource:檔案名稱
ofType:檔案格式
- (void)viewDidLoad{ [super viewDidLoad]; NSBundle *bundle=[NSBundle mainBundle]; // 擷取路徑的方法 // 載入資料 self.provinces=[NSArray arrayWithContentsOfFile:[bundle pathForResource:@"provinces" ofType:@"plist"]];// 擷取路徑需要上面的bundle self.cities=[NSDictionary dictionaryWithContentsOfFile:[bundle pathForResource:@"cities" ofType:@"plist"]];// 擷取路徑需要上面的bundle}
2.設定組數,通過對provinces.plist檔案中省份的count,來返回一共有多少組
#pragma mark -資料來源方法#pragma mark 一共多少組-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ // 返回省份的個數,也就是多少組 return self.provinces.count;}
3.設定第section組有多少行(先得到第i個組,通過這個組到數組中去調取有多少行,返回對應城市行數)
首先要設定property
@interface ViewController ()// 省份@property(nonatomic,strong)NSArray *provinces;// 城市@property (nonatomic,strong)NSDictionary *cities;@end
#pragma mark 第section組有多少行-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ // 返回省對應城市的成員個數 // 取出第section組的省份名稱 NSString *pName=self.provinces[section]; // 取出對應城市 NSArray *myCities=self.cities[pName]; // 返回對應城市成員個數 return myCities.count; }
4.用來返回某一行對應的資料
#pragma mark 返回某一行對應的資料-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ // 建立一個cell // UITableViewCellStyleDefault 是預設的style // reuseIdentifier 標識符預設為nil UITableViewCell *cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil]; // 1.首先取出第section組的省份名稱 NSString *pName= self.provinces[indexPath.section]; // 2.根據上面取出的省份名稱來取出這個省份的所有城市 NSArray *myCities=self.cities[pName]; // 取出對應的城市名稱 cell.textLabel.text=myCities[indexPath.row]; return cell;}
5.返回頭部標題
#pragma mark 返回頭部標題-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ return self.provinces[section];}
6.返回索引【此處是使用省份作為索引,如果用拼音首字母作為索引的話,需要調取第三方內容】
#pragma mark -添加索引條,標題索引-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{ //return @[@"A",@"B",@"C"]; // 返回所有省份 return self.provinces;}