您的位置:首页 > 移动开发 > IOS开发

IOS-OC之高级控件TableView之二

2016-02-17 15:46 681 查看
和前一篇TableView不一样的地方呢是分组,先来张效果图



.h的代码

#import <UIKit/UIKit.h>

//加UITableViewDataSource,UITableViewDelegate委托代理,具体代码在.m中实现
@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
//数据字典
@property (nonatomic, strong) NSDictionary *group;
//组名数组
@property (nonatomic, strong) NSArray *name;
//tableView声明
@property (strong, nonatomic) IBOutlet UITableView *tableView;

@end


.m代码

//返回每个组加载的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//组名
NSString *groupname = [_name objectAtIndex:section];
//根据组名获取当前组的数组
NSArray *group = [_group objectForKey:groupname];
return [group count];
}

//返回组数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return [_name count];
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
NSString *name = [_name objectAtIndex:section];
return name;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"CellIderterfier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *name = [_name objectAtIndex:section];
NSArray *group = [_group objectForKey:name];
cell.textLabel.text = [group objectAtIndex:row];
return cell;
}

//初始化
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSBundle *bundle = [NSBundle mainBundle];
获取数据字典的文件路径
NSString *filePath = [bundle pathForResource:@"statedictionary" ofType:@"plist"];
//根据路径获取到数据字典
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath];
//赋值
self.group = dict;
//数据字典的所有key值就是组名
self.name = [[_group allKeys] sortedArrayUsingSelector:@selector(compare:)];
}

//这个事件是点击某一行数据时执行的操作
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//组名
NSString *groupname = _name[indexPath.section];
//每组的数据
NSArray *group = [_group objectForKey:groupname];
//获取到当前点击这一行的数据用initWithFormat拼接成字符串
NSString *message = [[NSString alloc]initWithFormat:@"你选择了%@组的%@", groupname,group[indexPath.row]];
//这个是显示一个alert
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选中" message: message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:ok];
[self presentViewController:alert animated:YES completion:nil];
//点击后会有按下效果,这个是执行操作后消除这一行的效果
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end


数据字典plist图



nib文件



要拖对哦~~

tableView的style选择Grouped



很简单吧~~来试一试吧
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息