代码改变世界

初学IOS之TableView

2016-07-27 00:00  二十四个比利  阅读(372)  评论(0编辑  收藏  举报

PS:tableview作为IOS的UI界面的重点,今天我只学习一部分,在下文列出。

下文我以创建省份为例子,用纯代码的方式创建,但是并不是最优代码,仅作熟悉tableview的创建使用。

--------------------------------------------------------------------------------------------------------

step 1:在viewDidLoad中添加以下代码

//实例化一个tableview对象,其中self.view.bounds能够使tableview和控制器的view大小相同,tableview分两种style,第一种是UITableViewGrouped,分组表,第二种是plain table,

无格式表。如果在无格式表中加了索引,就成了索引表

 UITableView * tableview = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];

//设置tablview的代理 ,需要遵循协议-----><UITableViewDataSource,UITableViewDelegate>

tableview.dataSource = self;

 //加载到控制器中

[self.view addSubview:tableview];

//创建一个字典数组

  _allCities =@[

                  @{

                      @"cities":@[@"广州",@"东莞",@"深证",@"珠海"],

                      @"header":@"广东",

                      @"footer":@"广东很不错"

                      },

                  

                  @{

                      @"cities":@[@"杭州",@"宁波",@"温州",@"台州"],

                      @"header":@"浙江",

                      @"footer":@"浙江还可以"

                      },

                  @{

                      @"cities":@[@"南京",@"无锡",@"苏州",@"常州"],

                      @"header":@"江苏",

                      @"footer":@"江苏不错"

                      },

                  

                  ];

step 2:一共有多少组

#pragma mark 一共有多少组 section==

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return _allCities.count;

}

step 3:每组多少行

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    NSDictionary *dic = _allCities[section];

    NSArray *arr = dic[@"cities"];

    return arr.count;

}

step 4: 为每行的cell单元添加文字

 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    UITableViewCell * cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];

    NSDictionary *dic = _allCities[indexPath.section];

    NSArray *arr = dic[@"cities"];    

    cell.textLabel.text = arr[indexPath.row];

    return cell;    

}

step 5:为组添加表头,表脚

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{

    NSDictionary *dic = _allCities[section];

 

    

    return dic[@"header"];

}

 

- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section

{

    return _allCities[section][@"footer "];

}

//以下是结果 

 

//以下是总结