iOS高級控件之TableView(一)城市信息(1)

首頁,我們創建一個新的工程項目,並在storyboard上創建一個tableview的控件,並且右擊在上方可以看見letout上有兩個選項一個是dataSource數據源,另一個是delegate方法,我們分別點擊這個然後將其連接之view Controller
這裏寫圖片描述
然後我們要習慣性的在.h中添加協議

@interface ViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>

接着我們在didviewload中初始化數據,然後再開始設置數據源方法畢竟我們要在tableview中顯示的數據就是從數據源中獲得的(其中這個數據源,cities.plist & provinces.plist這兩個是我之前就創建好的plist文件,類型分別是NSDictionary和NSArray)
這裏寫圖片描述
這裏寫圖片描述

//初始化數據
NSBundle *bundle = [NSBundle mainBundle];
//城市字典
self.cities = [NSDictionary dictionaryWithContentsOfFile:[bundle pathForResource:@"cities" ofType:@"plist"]];
//省份數組
self.provinces =[NSArray arrayWithContentsOfFile:[bundle pathForResource:@"provinces" ofType:@"plist"]];

接着就是寫數據源方法

#pragma mark 數據源方法
#pragma mark 省份數量 section
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.provinces.count;
}
#pragma mark 每個城市數量
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //1.獲取對應的省名稱
    NSString *pName = self.provinces[section];
    //2.從字典中獲取該省的城市數組
    NSArray *cities = self.cities[pName];

    //3.返回城市數組數量
    return cities.count;

}
#pragma mark 表格單元顯示內容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];

    //1.獲取省份名稱
    NSString *pname = self.provinces[indexPath.section];
    //2.從字典中獲取省份中的城市數組
    NSArray *cities = self.cities[pname];
    //3.用城市數組中對應的行數設置單元格內容
    [cell.textLabel setText:cities[indexPath.row]];

    return  cell;

}

同時爲了日後相關功能實現,比如點擊某個單元格,會發生點啥,那麼就需要添加代理方法來實現

#pragma  mark 表格代理方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //1.獲取省份名稱
    NSString *pname = self.provinces[indexPath.section];
    //2.根據省的名稱獲取城市數組
    NSArray *cities = self.cities[pname];
    //3.從城市數組中獲取相應的的城市名稱
    NSString *cityName = cities[indexPath.row];
    //4.輸出用戶選擇
    NSLog(@"%@ ~ %@",pname,cityName);

}```


同時爲了方便用戶,再右側通常有一個索引,也很簡單

pragma mark 右側索引方法

-(NSArray ) sectionIndexTitlesForTableView:(UITableView )tableView
{
return self.provinces;
}
“`
現在效果就如圖所示,用戶可以點擊右側索引進行查找省份信息了

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章