iphone中UITableView的用法总结

来源:互联网 发布:加内特生涯数据排行 编辑:程序博客网 时间:2024/06/18 04:56

iOS UITableView的用法总结


[摘要]本文介绍iOS TableView的用法,包括通过动态数组NSMutableArray中的数据来显示数据和通过plist文件提供数据来显示数据,并提供详细的示例代码供参考。

通过两种方法来实现: 

一、通过动态数组NSMutableArray中的数据,来显示数据

1.新建Empty Application项目,新建ViewController,HomeViewController,在AppDelegate.m中导入该文件,并在方法- (BOOL)application:didFinishLaunchingWithOptions:中添加以下红色标记的代码。

View Row Code
1- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions2{3self.window=[[[UIWindowalloc]initWithFrame:[[UIScreenmainScreen]bounds]]autorelease];4// Override point for customization after application launch.5self.window.backgroundColor=[UIColorwhiteColor];67HomeViewController*homeViewController=[[HomeViewControlleralloc]init];8self.window.rootViewController= homeViewController;9[homeViewControllerrelease];1011[self.windowmakeKeyAndVisible];12returnYES13}

2.在 HomeViewController.xib上添加Table View控件

将其Outlets的dataSource和delegate与File's Owner建立关联,目的:

(1) dataSource: 向HomeViewController添加UITableViewDataSource协议,从而可以在该类中使用相关的协议方法,在Table View中显示数据。

(2) delegate :向HomeViewController添加UITableViewDelegate协议,从而可以在该类中使用相关的协议方法,响应用户在Table View中的交互操作。

在HomeViewController.h中添加协议:

View Row Code
1#import <UIKit/UIKit.h>2@interfaceHomeViewController : UIViewController3<UITableViewDelegate,UITableViewDataSource>{4}5@end

目的:都添加协议,有备无患。提高代码编写的效率和可靠性。

3. 在HomeViewController.m中编写代码

View Row Code
1#import"HomeViewController.h"2@interfaceHomeViewController ()3@end4@implementationHomeViewController5NSMutableArray*listOfContacts;//声明动态数组6- (void)viewDidLoad7{89listOfContacts=[[NSMutableArrayalloc]init];//分配内存并初始化1011[listOfContactsaddObject:@"张三"];12[listOfContactsaddObject:@"张1"];13[listOfContactsaddObject:@"张2"];14[listOfContactsaddObject:@"张3"];15[listOfContactsaddObject:@"张4"];16[listOfContactsaddObject:@"张5"];17[listOfContactsaddObject:@"张6"];18[listOfContactsaddObject:@"张7"];19[listOfContactsaddObject:@"张8"];20[listOfContactsaddObject:@"张9"];21[listOfContactsaddObject:@"张11"];22[listOfContactsaddObject:@"张12"];23[listOfContactsaddObject:@"张13"];24[listOfContactsaddObject:@"张14"];25[listOfContactsaddObject:@"张15"];26[listOfContactsaddObject:@"张16"];27[listOfContactsaddObject:@"张17"];28[listOfContactsaddObject:@"张18"];29[listOfContactsaddObject:@"张19"];3031[superviewDidLoad];32}33//使用UITableViewDataSource协议的tableView:cellForRowAtIndexPath:方法34//该方法用来将数据填充进Table View的单元格中35/*36在Table View中每填充一个单元格的数据就会触发一次该事件。37注意:如果我们的数据一共有200项,并不代表会连续触发200次这个事件,如果当前屏幕只能显示10行数据的话,就只会触发10次该事件,当用户滚动该Table View而产生新的单元格时,才会继续触发该事件。38*/39- (UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath*)indexPath{4041staticNSString*CellIndentifier=@"Contact";4243UITableViewCell*cell=[tableViewdequeueReusableCellWithIdentifier:CellIndentifier];44/*45dequeueReusableCellWithIdentifier方法,获取UITableViewCell类型的对象,而且获取的是一个已经在TableView中使用过并可以复用的对象。46想象一下:47如果数组中有1000个元素,我们为每一个元素都实例化一个UITableViewCell对象的话,系统就会内存溢出甚至崩溃。其实每个用户在一个屏幕中能够看到的单元格数量也就十几个,他们通过上下滚动屏幕的操作可以让一些已显示的单元格消除,而这些单元格对象系统就会保留下来以备我们需要显示新单元格时可以复用它们,从而达到了节省系统资源的目的。这个方法包含一个参数CellIdentifier, 它用于指明你需要哪个标识的可复用单元格。在同一界面中如果有多个表格的情况时非常有用。48当然如果没有获取到可复用的单元格时,我们就需要使用UITableViewCell的initWithStyle:reuseIdentifier:方法直接实例化一个单元格。其中reuseIdentifier参数用于设置该表格的可复用标识。49*/5051if (cell==nil) {52cell=[[[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIndentifier]autorelease];5354}5556NSString*cellValue=[listOfContactsobjectAtIndex:indexPath.row];57cell.textLabel.text= cellValue;5859//示意标志: Disclosure Indicator,Disclosure Button,Checkmark,默认为None6061//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;6263//cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;64//cell.accessoryType = UITableViewCellAccessoryCheckmark;65cell.accessoryType=UITableViewCellAccessoryNone;6667//单元格添加图片68UIImage*image=[UIImageimageNamed:@"avatar.png"];69cell.imageView.image= image;7071return cell;72}73//使用UITableViewDataSource协议的tableView:numberOfRowsInSection:方法74//该方法用来设置Table View中要显示数据的行数75- (NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section{76return[listOfContactscount];77}78//添加标题和脚本信息79- (NSString*)tableView:(UITableView*)tableViewtitleForHeaderInSection:(NSInteger)section{8081return@"联系人列表";828384}85- (NSString*)tableView:(UITableView*)tableViewtitleForFooterInSection:(NSInteger)section{86return@"作者:what if";87}888990//UITableViewDelegate协议的方法,选择表格中的项目91- (void)tableView:(UITableView*)tableViewdidSelectRowAtIndexPath:(NSIndexPath*)indexPath{92NSString*contactSelected=[listOfContactsobjectAtIndex:[indexPathrow]];93NSString*msg=[[NSStringalloc]initWithFormat:@"您选择的联系人:%@",contactSelected];94UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:@"选择联系人"message:msgdelegate:selfcancelButtonTitle:@"OK"otherButtonTitles:nil];95[alertshow];96[alertrelease];97[contactSelectedrelease];98[msgrelease];99}100//UITableViewDelegate协议的方法,表格中的缩进101- (NSInteger)tableView:(UITableView*)tableViewindentationLevelForRowAtIndexPath:(NSIndexPath*)indexPath{102return[indexPathrow]%9;103104 105- (void)dealloc{106107108[listOfContactsrelease];109[superdealloc];110111}112- (void)viewDidUnload113{114[superviewDidUnload];115}116- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation117{118return (interfaceOrientation==UIInterfaceOrientationPortrait);119}120@end

二、通过plist文件提供数据,来显示数据,方便分组

1.添加contacts.plist文件

2. HomeViewController.h中添加代码

View Row Code
1#import <UIKit/UIKit.h>2@interfaceHomeViewController : UIViewController3<UITableViewDelegate,UITableViewDataSource>{4}5@property (nonatomic, retain)NSDictionary*contactTitles;//存储所有的联系人信息6@property (nonatomic, retain)NSArray*groups;//所有分类名称存入数组中7@end

3. HomeViewController.m中添加代码

View Row Code
1#import"HomeViewController.h"2@interfaceHomeViewController ()3@end4@implementationHomeViewController5@synthesize contactTitles;6@synthesize groups;7- (void)viewDidLoad8{910NSString*path=[[NSBundlemainBundle]pathForResource:@"contacts"ofType:@"plist"];//plist文件路径11NSDictionary*dict=[[NSDictionaryalloc]initWithContentsOfFile:path];12self.contactTitles= dict;13[dictrelease];1415NSArray*array=[[contactTitlesallKeys]sortedArrayUsingSelector:@selector(compare:)];1617self.groups= array;18[superviewDidLoad];19}20//使用UITableViewDataSource协议的tableView:cellForRowAtIndexPath:方法21- (UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath*)indexPath{2223staticNSString*CellIndentifier=@"Contact";2425UITableViewCell*cell=[tableViewdequeueReusableCellWithIdentifier:CellIndentifier];2627if (cell==nil) {28cell=[[[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIndentifier]autorelease];2930}313233NSString*group=[groupsobjectAtIndex:[indexPathsection]];34NSArray* contactSection=[contactTitlesobjectForKey:group];35cell.textLabel.text=[contactSectionobjectAtIndex:[indexPathrow]];363738//单元格添加图片39UIImage*image=[UIImageimageNamed:@"avatar.png"];40cell.imageView.image= image;414243return cell;44}45- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView{46return[groupscount];47}48//使用UITableViewDataSource协议的tableView:numberOfRowsInSection:方法49//该方法用来设置Table View中要显示数据的行数50- (NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section{5152NSString*group=[groupsobjectAtIndex:section];53NSArray*contactSection=[contactTitlesobjectForKey:group];5455return[contactSectioncount];56}57//添加标题和脚本信息58- (NSString*)tableView:(UITableView*)tableViewtitleForHeaderInSection:(NSInteger)section{59NSString*group=[groupsobjectAtIndex:section];60return group;6162}63- (NSString*)tableView:(UITableView*)tableViewtitleForFooterInSection:(NSInteger)section{64return@"作者:what if";65}666768/*//UITableViewDelegate协议的方法,选择表格中的项目69- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{70NSString *contactSelected = [listOfContacts objectAtIndex:[indexPath row]];71NSString *msg = [[NSString alloc] initWithFormat:@"您选择的联系人:%@", contactSelected];72UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"选择联系人" message:msg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];73[alert show];74[alert release];75[contactSelected release];76[msg release];77} */78/*79//UITableViewDelegate协议的方法,表格中的缩进80- (NSInteger) tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath{81return [indexPath row] % 9;8283}*/84//索引功能8586- (NSArray*)sectionIndexTitlesForTableView:(UITableView*)tableView{87return groups;88}89//用户点击标志后触发的事件,只有DetailDisclosure Button才有该事件90- (void)tableView:(UITableView*)tableViewaccessoryButtonTappedForRowWithIndexPath:(NSIndexPath*)indexPath{91//进入到该项目的详细信息页面92}939495- (void)dealloc{9697[contactTitlesrelease];98[groupsrelease];99[superdealloc];100101}102- (void)viewDidUnload103{104[superviewDidUnload];105}106- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation107{108return (interfaceOrientation==UIInterfaceOrientationPortrait);109}110@end

4.在xib文件中修改其Style为Grouped

显示效果:

iOS TableView


开发多个Section的tableView。

首先应该考虑到数据源该如何得到

我们这里可以通过两种方式:第一种是读取plist文件。第二种是通过代码进行数据存储以及读取。

多个Section需要的数据源是一个字典,字典里的内容是一个数组。在plist文件中可以这样去创建



在.h文件中定义一个字典,一个数组



在.m文件的viewDidLoad函数中:


解释一下:通过bundle得到整个程序的沙盒,新建NSURL对象,读取到一个字典中,然后取所有的字典key存储到一个数组中。


接下来就是实现TableView的代理和数据源函数啦


section数量取的是字典重元素的count值;

每个section的行数区的是相对应的字典元素数组的count值.

cellForRowAtIndexPath中的内容就直接取值显示。


下面要对tableView每个section加标题:


下面是要增加tableview右侧的索引栏:



效果也就完成啦:

看看效果吧

右面是拉动索引栏时的效果图。


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 孩子上课不认真听讲怎么办 孩子做什么都慢怎么办 7岁上课不听讲怎么办 打孩子脸肿了怎么办 一岁宝宝太调皮怎么办 怀孕早期喝了酒怎么办 怀孕期间喝了酒怎么办 一岁宝宝多动怎么办 3岁前儿童多动症怎么办 好动症的孩子该怎么办 18个月宝宝腹泻怎么办 8个月小孩发烧怎么办 八个月大宝宝发烧怎么办 8个月宝宝拉稀水怎么办 八个月宝宝38度怎么办 8个月的宝宝发烧怎么办 八个月大的宝宝拉肚子怎么办 9孩子上课坐不住怎么办 3岁宝宝太皮怎么办 4岁的宝宝多动症怎么办 小孩好动注意力不集中怎么办 乐扣加热变形了怎么办 3岁宝宝咳嗽厉害怎么办 六个月婴儿呕奶怎么办 刚出生婴儿呕奶怎么办 宝宝拉颗粒便便怎么办 奶水不够宝宝又不吃奶粉怎么办 一岁突然不吃饭怎么办 母乳不够吃宝宝不吃奶粉怎么办 八个月不吃辅食怎么办 孩子长得太快怎么办 反复发烧到39度怎么办 儿童发烧到39度怎么办 7岁儿童发烧40度怎么办 7岁反复发烧39度怎么办 宝宝烧到39.5度怎么办 3岁儿童发烧39度怎么办 孩子发高烧怎么办39度5 3岁宝宝不吃水果怎么办 2岁宝宝不吃水果怎么办 4岁宝宝不吃水果怎么办