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

ios学习--TableView详细解释

2013-07-11 23:44 330 查看
-、建立 UITableView

DataTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 420)];
[DataTable setDelegate:self];
[DataTable setDataSource:self];
[self.view addSubview:DataTable];
[DataTable release];

二、UITableView各Method说明

//添加索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
return TitleData;
}

// Section Titles
//每个section显示的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return @"";
}

//指定有多少个分区(Section),默认为1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 4;
}

//指定每个分区中有多少行,默认为1
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
}

//绘制Cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
SimpleTableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier: SimpleTableIdentifier] autorelease];
}
cell.imageView.image=image;//未选cell时的图片
cell.imageView.highlightedImage=highlightImage;//选中cell后的图片
cell.text=//.....
return cell;
}

//行缩进
-(NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath{
NSUInteger row = [indexPath row];
return row;
}

//改变行的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 40;
}

//定位
[TopicsTable setContentOffset:CGPointMake(0, promiseNum * 44 + Chapter * 20)];

//返回当前所选cell
NSIndexPath *ip = [NSIndexPath indexPathForRow:row inSection:section];
[TopicsTable selectRowAtIndexPath:ip animated:YES scrollPosition:UITableViewScrollPositionNone];

[tableView setSeparatorStyle:UITableViewCellSelectionStyleNone];

//选中Cell响应事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];//选中后的反显颜色即刻消失
}

//判断选中的行(阻止选中第一行)
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
if (row == 0)
return nil;

return indexPath;
}

//划动cell是否出现del按钮
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
}

//编辑状态
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{

[topicsTable setContentSize:CGSizeMake(0,controller.promiseNum * 44)];
//右侧添加一个索引表
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
}
//返回Section标题内容
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
}
//自定义划动时del按钮内容
- (NSString *)tableView:(UITableView *)tableView
titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
//跳到指的row or section
[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
三、在UITableViewCell上建立UILable多行显示
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
UILabel *Datalabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 320, 44)];
[Datalabel setTag:100];
Datalabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:Datalabel];
[Datalabel release];
}
UILabel *Datalabel = (UILabel *)[cell.contentView viewWithTag:100];
[Datalabel setFont:[UIFont boldSystemFontOfSize:18]];
Datalabel.text = [data.DataArray objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
//选中cell时的颜色
typedef enum {
UITableViewCellSelectionStyleNone,
UITableViewCellSelectionStyleBlue,
UITableViewCellSelectionStyleGray
} UITableViewCellSelectionStyle
//cell右边按钮格式
typedef enum {
UITableViewCellAccessoryNone, // don't show any accessory view
UITableViewCellAccessoryDisclosureIndicator, // regular chevron. doesn't track
UITableViewCellAccessoryDetailDisclosureButton, // blue button w/ chevron. tracks
UITableViewCellAccessoryCheckmark // checkmark. doesn't track
} UITableViewCellAccessoryType
//是否加换行线
typedef enum {
UITableViewCellSeparatorStyleNone,
UITableViewCellSeparatorStyleSingleLine
} UITableViewCellSeparatorStyle//改变换行线颜色
tableView.separatorColor = [UIColor blueColor];

转自:http://no001.blog.51cto.com/1142339/637651

一、概述

我们经常需要显示大量数据,比如iPhone内置的通讯录应用。UITableView是UIScrollView的子类。在iPhone中,表视图是iPhone上的一个列,多个行的表;用户可以上下滚动来查看更多的数据。从用户的角度来看,创建一个表视图就是完成下面三个功能:

创建表视图

为每一行提供文本或图像

当用户选择某一行时,做出响应

一个表视图必须有个一个数据源,这是通过UITableViewDataSource协议来完成的。另外表视图通过UITableViewDelegate协议来实现表视图上的操作。一般而言,你会创建一个UITableViewController的子类,然后在这个子类上实现数据源和表视图的操作。

1.1 表视图的类型

表视图的显示风格分为两类:

1、不分组的显示---UITableViewStylePlain

2、分组的显示---UITableViewStyleGrouped

对于分组的结构,每组叫做section,在section的每一行叫做表单元(Table Cell)

二、UITableView的常用方法

2.1 初始化一个表视图的方法

- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style ;

2.2 表视图的相关配置方法

- (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier ;//根据唯一标识,查找可重用表视图单元(UITableViewCell)对象

- (NSInteger)numberOfRowsInSection:(NSInteger)section ;//返回指定section的表视图行数

- (NSInteger)numberOfSections ;//返回表视图中的section数目

2.3 访问section和表单元(UITableViewCell)

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath ;//返回指定NSIndexPath的表单元,NSIndexPath对象代表在一个嵌套数组集合树的特定节点的路径。这条道路被称为索引路径。此处只要将NSIndexPath理解为一个可代表表单元位置的一个路径,根据这个NSIndexPath路径,可用定位到对应的表单元。

- (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell ;//返回指定表单元的NSIndexPath路径信息

- (NSIndexPath *)indexPathForRowAtPoint:(CGPoint)point;//返回指定了CGPoint的NSIndexPath路径信息

- (NSArray *)indexPathsForRowsInRect:(CGRect)rect;//返回指定CGRect的NSIndexPath路径信息数组

- (NSArray *)visibleCells;//返回可见的表单元(UITableViewCell)数组

- (NSArray *)indexPathsForVisibleRows;//返回可见的表单元的NSIndexPath路径信息数组

2.4 管理section

- (NSIndexPath *)indexPathForSelectedRow;//返回选中行的NSIndexPath路径信息

- (void)selectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UITableViewScrollPosition)scrollPosition;//

- (void)deselectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated;//

2.5 插入和删除表单元(UITableViewCell)

- (void)beginUpdates

- (void)endUpdates

- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

- (void)insertSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation

- (void)deleteSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation

- (void)setEditing:(BOOL)editing animated:(BOOL)animate

2.6 表视图数据的加载

- (void)reloadData

- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation

- (void)reloadSectionIndexTitles

ios开发学习笔记3:表视图

2011-09-20 16:44:05| 分类: ios|字号 订阅

#pragma mark -
#pragma mark table view data source methods

//返回某个表视图有多少行数据
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.listData.count;
}

//表视图显示表视图项时调用:第一次显示(根据视图大小显示多少个视图项就调用多少次)以及拖动时调用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"simpleTableIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (!cell) {
//有4种style,default只显示image和文本标签;subtitle显示image,文本标签和详细文本(位于文本标签下方);value1显示image,文//本标签和详细文本(位于文本标签右边);value2只显示文本标签和详细文本(文本标签小字体,详细文本粗体)
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier] autorelease];
}

UIImage *image = [UIImage imageNamed:@"apple.png"];
cell.imageView.image = image;
UIImage *image2 = [UIImage imageNamed:@"cherry.png"];
cell.imageView.highlightedImage = image2;

NSUInteger row = indexPath.row;
cell.textLabel.text = [listData objectAtIndex:row];
cell.textLabel.font = [UIFont boldSystemFontOfSize:50];

if (row < 7) {
cell.detailTextLabel.text = @"Mr Disney";
}
else{
cell.detailTextLabel.text = @"Mr Tolkein";
}

return cell;
}

/*以下4个方法适用于创建分区表和索引分区表的委托方发*/
//设置分区个数
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return keys.count;
}

//设置每个分区的标题
- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [keys objectAtIndex:section];
}

//创建右侧索引表,返回需要显示的索引表数组
- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView
{
return keys;
}

//点击右侧索引表项时调用

- (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index

{

NSString *key = [keys objectAtIndex:index];

NSLog(@"sectionForSectionIndexTitle key=%@",key);

if (key == UITableViewIndexSearch) {

[table setContentOffset:CGPointZero animated:NO];

return NSNotFound;

}

return index;

}

#pragma mark -
#pragma mark table delegate methods

//设置每行缩进级别
- (NSInteger) tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
{
return indexPath.row;
}

//在某行被选中前调用,返回nil表示该行不能被选中;另外也可返回重定向的indexPath,使选择某行时会跳到另一行
- (NSIndexPath *) tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = indexPath.row;
if (row == 0) {
return nil;
}

return indexPath;
}

//某行已经被选中时调用
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = indexPath.row;
NSString *rowValue = [listData objectAtIndex:row];

NSString *message = [[NSString alloc] initWithFormat:@"you selected %@", rowValue];

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"row selected" message:message delegate:nil cancelButtonTitle:@"yes, I did" otherButtonTitles:nil];
[alert show];

[message release];
[alert release];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//设置行高度
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 70;
}

在iOS应用中,UITableView应该是使用率最高的视图之一了。iPod、时钟、日历、备忘录、Mail、天气、照片、电话、短信、Safari、App Store、iTunes、Game Center⋯几乎所有自带的应用中都能看到它的身影,可见它的重要性。
然而在使用第三方应用时,却经常遇到性能上的问题,普遍表现在滚动时比较卡,特别是table cell中包含图片的情况时。
实际上只要针对性地优化一下,这种问题就不会有了。有兴趣的可以看看LazyTableImages这个官方的例子程序,虽然也要从网上下载图片并显示,但滚动时丝毫不卡。
下面就说说我对UITableView的了解。不过由于我也是初学者,或许会说错或遗漏一些,因此仅供参考。

首先说下UITableView的原理。有兴趣的可以看看《About Table Views in iOS-Based Applications》
UITableView是UIScrollView的子类,因此它可以自动响应滚动事件(一般为上下滚动)。
它内部包含0到多个UITableViewCell对象,每个table cell展示各自的内容。当新cell需要被显示时,就会调用tableView:cellForRowAtIndexPath:方法来获取或创建一个cell;而不可视时,它又会被释放。由此可见,同一时间其实只需要存在一屏幕的cell对象即可,不需要为每一行创建一个cell。
此外,UITableView还可以分为多个sections,每个区段都可以有自己的head、foot和cells。而在定位一个cell时,就需要2个字段了:在哪个section,以及在这个section的第几行。这在iOS SDK中是用NSIndexPath来表述的,UIKit为其添加了indexPathForRow:inSection:这个创建方法。
其他诸如编辑之类的就不提了,因为和本文无关。

介绍完原理,接下来就开始优化吧。

使用不透明视图。
不透明的视图可以极大地提高渲染的速度。因此如非必要,可以将table cell及其子视图的opaque属性设为YES(默认值)。
其中的特例包括背景色,它的alpha值应该为1(例如不要使用clearColor);图像的alpha值也应该为1,或者在画图时设为不透明。

不要重复创建不必要的table cell。
前面说了,UITableView只需要一屏幕的UITableViewCell对象即可。因此在cell不可见时,可以将其缓存起来,而在需要时继续使用它即可。
而UITableView也提供了这种机制,只需要简单地设置一个identifier即可:

static NSString *CellIdentifier = @"xxx";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

值得一提的是,cell被重用时,它内部绘制的内容并不会被自动清除,因此你可能需要调用setNeedsDisplayInRect:或setNeedsDisplay方法。
此外,在添加table cell的时候,如果不需要动画效果,最好不要使用insertRowsAtIndexPaths:withRowAnimation:方法,而是直接调用reloadData方法。因为前者会对所有indexPaths调用tableView:cellForRowAtIndexPath:方法,即便该cell并不需要显示(不知道是不是bug),这就可能创建大量多余的cell。勘误:只是在模拟器上测试如此,真机调试时没有这种bug。

减少视图的数目。
UITableViewCell包含了textLabel、detailTextLabel和imageView等view,而你还可以自定义一些视图放在它的contentView里。然而view是很大的对象,创建它会消耗较多资源,并且也影响渲染的性能。
如果你的table cell包含图片,且数目较多,使用默认的UITableViewCell会非常影响性能。奇怪的是,使用自定义的view,而非预定义的view,明显会快些。
当然,最佳的解决办法还是继承UITableViewCell,并在其drawRect:中自行绘制:

- (void)drawRect:(CGRect)rect {
if (image) {
[image drawAtPoint:imagePoint];
self.image = nil;
} else {
[placeHolder drawAtPoint:imagePoint];
}

[text drawInRect:textRect withFont:font lineBreakMode:UILineBreakModeTailTruncation];
}

不过这样一来,你会发现选中一行后,这个cell就变蓝了,其中的内容就被挡住了。最简单的方法就是将cell的selectionStyle属性设为UITableViewCellSelectionStyleNone,这样就不会被高亮了。
此外还可以创建CALayer,将内容绘制到layer上,然后对cell的contentView.layer调用addSublayer:方法。这个例子中,layer并不会显著影响性能,但如果layer透明,或者有圆角、变形等效果,就会影响到绘制速度了。解决办法可参见后面的预渲染图像。

不要做多余的绘制工作。
在实现drawRect:的时候,它的rect参数就是需要绘制的区域,这个区域之外的不需要进行绘制。
例如上例中,就可以用CGRectIntersectsRect、CGRectIntersection或CGRectContainsRect判断是否需要绘制image和text,然后再调用绘制方法。

预渲染图像。
你会发现即使做到了上述几点,当新的图像出现时,仍然会有短暂的停顿现象。解决的办法就是在bitmap context里先将其画一遍,导出成UIImage对象,然后再绘制到屏幕,详细做法可见《利用预渲染加速iOS设备的图像显示》

不要阻塞主线程。
做到前几点后,你的table view滚动时应该足够流畅了,不过你仍可能让用户感到不爽。常见的现象就是在更新数据时,整个界面卡住不动,完全不响应用户请求。
出现这种现象的原因就是主线程执行了耗时很长的函数或方法,在其执行完毕前,无法绘制屏幕和响应用户请求。其中最常见的就是网络请求了,它通常都需要花费数秒的时间,而你不应该让用户等待那么久。
解决办法就是使用多线程,让子线程去执行这些函数或方法。这里面还有一个学问,当下载线程数超过2时,会显著影响主线程的性能。因此在使用ASIHTTPRequest时,可以用一个NSOperationQueue来维护下载请求,并将其maxConcurrentOperationCount设为2。而NSURLRequest则可以配合GCD来实现,或者使用NSURLConnection的setDelegateQueue:方法。
当然,在不需要响应用户请求时,也可以增加下载线程数,以加快下载速度:

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
if (!decelerate) {
queue.maxConcurrentOperationCount = 5;
}
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
queue.maxConcurrentOperationCount = 5;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
queue.maxConcurrentOperationCount = 2;
}

此外,自动载入更新数据对用户来说也很友好,这减少了用户等待下载的时间。例如每次载入50条信息,那就可以在滚动到倒数第10条以内时,加载更多信息:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if (count - indexPath.row < 10 && !updating) {
updating = YES;
[self update];
}
}
// update方法获取到结果后,设置updating为NO

还有一点要注意的就是当图片下载完成后,如果cell是可见的,还需要更新图像:

NSArray *indexPaths = [self.tableView indexPathsForVisibleRows];
for (NSIndexPath *visibleIndexPath in indexPaths) {
if (indexPath == visibleIndexPath) {
MyTableViewCell *cell = (MyTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
cell.image = image;
[cell setNeedsDisplayInRect:imageRect];
break;
}
}
// 也可不遍历,直接与头尾相比较,看是否在中间即可。

最后还是前面所说过的insertRowsAtIndexPaths:withRowAnimation:方法,插入新行需要在主线程执行,而一次插入很多行的话(例如50行),会长时间阻塞主线程。而换成reloadData方法的话,瞬间就处理完了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: