這篇博文整理的很好,我網上看道 的,寫的詳細的都在這裏面了!html
原文地址:http://blog.csdn.net/ch_soft/article/details/6945987。數組
首先、對UITableView進行講解,下面有對它進行實際的應用框架
UITableView
iphone
顯示大型內容的列表ide
單行,多列函數
垂直滾動,沒有水平滾動
佈局
大量的數據集性能
性能強大,並且廣泛存在於iPhone的應用程序中學習
TableView Styles
UITableView有兩個默認的內置風格,第一個是UITableViewStylePlain(簡明風格,簡明風格代表表格視圖自身沒有真正地在你本身實際地提供任何外觀以前提供不少的外觀,大部分狀況下,它會作的惟一的事情是它會給你這些header和footer,在頂部的章節header有章節F,它是當前固定在屏幕的頂部,即便你滾動那個內容章節的header F會保持在那裏,直到全部F的內容都移走,而後它滾出去。表格視圖還提供你在右邊的索引部分,那隻用在簡易風格的表格視圖中,你可以獲取它。)另外一種風格是UITableViewStyleGrouped風格(組團風格),UITableViewStyleGrouped表格視圖是UIKit提供的另一個默認風格,它給圍繞章節分段的外觀,它是垂直條紋的背景,頂部是白色圓形分段,你默認經過UITableView:StyleGrouped得到該類型的外觀。
表格視圖以及組成部分
在頂部,咱們有表格header,它是UITableView上的一個可設置的屬性,它只是個UIView,你能建立任何UIView子類或用UIImageView或UILable分配並設置它們爲表格視圖的tableheader view ,而後表格視圖會安置它到你其他的內容之上,它會隨着內容上下滾動。
在表格視圖的內容底部,咱們有表格footer,與header同樣是UIView的任意子視圖,它是你設置的UITableView的屬性,而後表格視圖會安置它到你其他的內容之下,在表格header和footer視圖之間的是章節內容。
在章節中,有章節的header和章節的footer,在它們之間是全部的獨立單元,就是Tablecell。以下圖:
使用TableViews
在表格視圖中顯示數據
定製顯示的外觀和行爲
一個直接的解決方法
表格視圖用來顯示一列數據,因此使用一個數組
[myTableView setList : myListOfStuff];//該方法不存在,想法比較天真
該方法爭議性
全部的數據必須事先裝載
全部的數據都裝載在內存中
更加靈活的方案
另一個對象爲表格視圖提供數據
不是一次性所有取得
只取如今須要展現的數據
像一個委託,它是純粹的數據導向,它只向數據源詢問數據
UITableViewDataSource(數據源協議)
提供章節和行的數目
//optionalmethod ,default to 1 if not implemented
-(NSInteger)numberOfSectionsInTableView:(UITableView*)tableView;
//requiredmethod
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
必要的時候向表格視圖提供所要顯示的cells
//required method
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;//在該方法中,UITableViewCell是UIView的一個子類,它知道如何在表格視圖滾軸,知道如何繪製分組風格表格視圖和組羣風格表格視圖,它必須本身是一個UITableViewCell或者UITableViewCell的子類。
NSIndexPath
是Foundation框架中的一個普通的類,它提供了到嵌套數列的樹中特定節點的路徑,事實上,它是一個整數陣列,表格視圖使用這個去表如今特定章節中的特定行,UITableView用的全部索引路徑正好有兩個元素,第一個是章節,第二個是行。
NSIndexPath和TableViews
@interfaceNSIndexPath (UITableView) {
}
+(NSIndexPath*)indexPathForRow:(NSUInteger)row inSection:(NSUInteger)section;
@property(nonatomic,readonly)NSUIntegerrow;
@property(nonatomic,readonly)NSUIntegersection;
@end
SingleSection Table View
返回行數
-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
return[myStringcount];
}
請求時提供一個單元
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
UITableViewCell*cell = ......;
cell.textLabel.text=[myStringobjectAtIndex:indexPath.row];
return[cell autorelease];
}
單元複用(cellreuse)
當你輕滑屏幕,你必須一次滾動上百行的文字,不少不少的不一樣單元,它不會完成的很好,每次一個消失,你破壞呢個表格視圖單元,而後爲下一個建立新的,咱們最終會作的是當一個表格視圖單元從頂部消失,它會放在一個複用隊列中,而且在你的TableViewCellforRowIndexPath方法中,你能夠選擇,固然你應該老是這樣作,你有機會去在分配新的單元前,向表格視圖詢問複用隊列其中的一個單元,若是一個單元已經從頂部滾軸消失,對於顯示當前可視的東西,它不會必須的,你能取得它改變它的內容爲你所須要顯示的新行而它會被從新滾進底部。(有點像循環瀑布)
-(UITableViewCell*)dequeueReusableCellWithindentifier:(NSString*)identifier;
//取回可複用的一個單元
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
UITableViewCell*cell = [tableViewdequeueReusableCellWithIdentifier:@"MyIdentifier"];
if(cell== nil){
cell=[[[UITableViewCell alloc] initWithStyle:.....reuseIdentifier:@"MyIdentifier"]autorelease];
}
cell.text= [myStringobjectAtIndex:indexPath.row];
returncell;
}
觸發一個更新
何時數據源會被請求數據
當一行變得可視
徹底更新會被響應當使用reloadData
-(void)viewWillAppear:(BOOL)animated {
[superviewWillAppear:animated]; //全部的數據從新被加載,而後在放到複用隊列中
[self.tableViewreloadData];
}
章節和行進行重載數據
-(void)insertSections:(NSIndexSet*)sectionswithRowAnimation:(UITableViewRowAniamtion)animation;//能夠插入整個章節
-(void)ideleteSections:(NSIndexSet*)sectionswithRowAnimation:(UITableViewRowAniamtion)animation;//能夠刪除整個章節
-(void)reloadSections:(NSIndexSet*)sections withRowAnimation:
(UITableViewRowAniamtion)animation;//在iPhoneos 3.0中重載章節數據(上面兩個方法的合併)
它們能重載部分的數據,而不會把全部東西都丟掉
-(void)insertRowsAtIndexPaths:(NSArray*)indexPahts withRowAnimation:(UITableViewRowAniamtion)animation;
-(void)deleteRowsAtIndexPaths:(NSArray*)indexPahts withRowAnimation:(UITableViewRowAniamtion)animation;
-(void)reloadRowsAtIndexPaths:(NSArray*)indexPahts withRowAnimation:(UITableViewRowAniamtion)animation;
其它的數據源方法
爲章節的header和footer設置標題(表格的header和footer是表格視圖上的屬性,你只分配那些視圖章節header和footer是依據章節的,所以它們由委派功能所提供)
容許編輯和重排單元
外觀和行爲
UITableViewDelegate
可定製外觀和行爲
邏輯獨立於視圖
數據源和委派常常是相同的對象(事實上,不多狀況下數據源不是委派)
表格視圖的外觀和行爲
定製表格視圖單元的外觀
-(void)tableView:(UITableView *) tableView willDisplayCell:(UITableViewCell *)cellforRowAtIndexPath:(NSIndexPath *)indexPath;
這個會在表格視圖的其中一個單元變爲可視前馬上被調用,它是你在表格視圖單元顯示在屏幕上以前的外觀定製的最後機會,它保證一旦你調用這個方法,咱們不會涉及任何單元的外觀,這以後,你改變的任何東西都會顯示在屏幕上,若是有一些東西你可能在TableViewcellForRowAtIndexPath方法中不知道,你想稍微懶惰地作這個,這會在那以後最後的機會去修改外觀。
驗證和響應所選擇的變化
使用表格視圖委派功能,對於選擇會有不一樣的功能
-(NSIndexPath*)tableView:(UITableView *)tableViewwillSelectRowAtIndexPath:(NSIndexPath *)indexPath;
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath;//用戶選擇完成擡起手指,在該方法中,你可能決定去分配新的UIViewController,而後推它到self.navigationContrller,所以一些新事物滑進來,行選擇一般會觸發一個事件。選擇一般不是一個持續的事情,它一般不會在你輕敲以後保持選擇狀態,一般會談出選擇而後完成一個行爲,或者你把它滑出屏幕,固然滑回來時會淡出。在iphone應用程序中你也會看到連續的選擇,咱們在表格試圖中是支持持續選擇的,若是用戶選擇一行而你沒有反選它,咱們不會替你反選,過去在iPhoneOS 2.0中不是這樣的,若是你不反選它,這個行爲是不肯定的,咱們如今支持這個持續選擇行爲。
響應選擇
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
NSIntegerrow = indexPath.row ;
idobjectToDispaly = [myObjects ObjectAtIndex:row ];
MyViewController* myViewController = …....;
myViewController.object = objectToDispaly ;
[self.navigationControllerpushViewController: myViewController animated:YES];
}
修改和禁用選擇
-(NSIndexPath*)tableView:(UITableView *)tableViewwillSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row== ….) {
returnnil;
}
else{ return indexPath ;}
}
UITableViewController
是UIViewController的子類,若是你想用全屏表格試圖風格,它會是很便利的起點,表格試圖會被自動建立,這包括控制器,表格視圖,數據源和委派,它在你第一次出現時替你調用reloadData,它在用戶導航回去時反選,會知道你以前所選的item。UITableViewController在正確的時間替你處理反選的事情,它還會閃爍滾動指示條,實際上這是iPhone人機界面的一部分。
TableView cells
指定的初始化程序
-(id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier ;
//舊的版本,如今已經不是默認的初始化程序了
-(id)initWithStyle:(UITableviewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier ;
//新版本
單元風格(cellstyle)
基本屬性
UITableViewCell有一個圖像視圖和一到兩個的文本標籤
cell.imageView.image= [UIImage imageNamed:@」vitolidok.png」];
cell.textLabel.text= @」Vitol Idol」;
cell.detailTextLabel.text=@」Billy Idol」;
效果如圖:
若是你在表格視圖單元的默認風格上設置detailTextLabel.text,它是不會作任何事情,由於它不顯示一個額外的detailText。
附件類型
//UITableView委託方法
-(UITableViewCellAccessoryType)tableView:(UITableView*)table accessoryTypeForRowWithIndexPath:(NSIndexPath *) indexPath;
-(void)tableView:(UITableView *)tableViewaccessoryButtonTappedForRowWithIndexPath:(NSIndexPath *) indexPath {
//只有是在藍色描述的按鈕(也就是上面的第二個)
NSIntegerrow = indexPath.row.
}
定製內容視圖
在有些狀況下,簡單的圖像和文本是不夠的
UITableViewCell有一個contentview 屬性
爲contentview 添加額外的視圖
-(UITableViewCell*) tableView :(UITableView) tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell*cell = ….......;
CGRectframe = cell.contentView.bounds;
UILabel*myLabel = [[UILabel alloc] initWithFrame :frame];
myLabel.text= ….;
[cell.contentViewaddSubview : myLabel];
[myLabelrelease];
}
其次,實際的使用方法
第一種,正常的使用方法
//
// TableViewViewController.m
// TableView
//
// Created by ch_soft on 11-11-7.
// Copyright 2011年 __MyCompanyName__. All rights reserved.
//
#import "TableViewViewController.h"
@implementation TableViewViewController
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
dataArray = [[NSMutableArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5",nil];
edit=NO;
[super viewDidLoad];
UIButton * button=[UIButton buttonWithType:UIButtonTypeCustom];
button.frame=CGRectMake(10,10, 60,20);
[button addTarget:self action:@selector(edit:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"eidt" forState:UIControlStateNormal];
[self.view addSubview:button];
//建立一個tableview
tableview=[[UITableView alloc] initWithFrame:CGRectMake(10, 40, 300, 400) style:UITableViewStylePlain];
[self.view addSubview:tableview];
tableview.delegate=self;
tableview.dataSource=self;
[tableview release];
}
-(void)edit:(id)sender
{
[tableview setEditing:!tableview.editing animated:YES];
if (edit) {
edit=NO;
[tableview setEditing:NO];
}else
{
edit=YES;
[tableview setEditing:YES];
}
}
#pragma mark TableView Delegate
//對編輯的狀態下提交的事件響應
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"commond eidting style ");
if (editingStyle == UITableViewCellEditingStyleDelete) {
[dataArray removeObjectAtIndex:indexPath.row];
// Delete the row from the data source.
[tableview deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
//響應選中事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"did selectrow");
}
//行將顯示的時候調用
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"will display cell");
}
//點擊了附加圖標時執行
-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"accessoryButtonTappedForRowWithIndexPath");
}
//開始移動row時執行
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath
{
NSLog(@"moveRowAtIndexPath");
}
//開發能夠編輯時執行
-(void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"willBeginEditingRowAtIndexPath");
}
//選中以前執行
-(NSIndexPath*)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"willSelectRowAtIndexPath");
return indexPath;
}
//將取消選中時執行
-(NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"willDeselectRowAtIndexPath");
return indexPath;
}
//移動row時執行
-(NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
NSLog(@"targetIndexPathForMoveFromRowAtIndexPath");
//用於限制只在當前section下面才能夠移動
if(sourceIndexPath.section != proposedDestinationIndexPath.section){
return sourceIndexPath;
}
return proposedDestinationIndexPath;
}
//刪除按鈕的名字
-(NSString*)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @"刪除按鈕的名字";
}
//讓表格能夠修改,滑動能夠修改
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
//讓行能夠移動
-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
//
NSLog(@"手指撮動了");
return UITableViewCellEditingStyleDelete;
}
#pragma mark TableView DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [dataArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString * indetify=@"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:indetify];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indetify];
}
cell.textLabel.text=[dataArray objectAtIndex:indexPath.row];
cell.accessoryType=UITableViewCellAccessoryCheckmark;//添加附加的樣子
return cell;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
第二種,使用自定義UITbaleViewCell方法。
其實很簡單,只須要定義一個UItableViewCell的子類,而後在初始化cell的時候,使用自定義的cell生成cell就能夠了。
@interface CustomTableCell :UITableViewCell {
}
@end
上篇文章介紹瞭如何用UITableView顯示錶格,並講了幾種UITableViewCell的風格。不過有時候咱們須要本身定義UITableViewCell的風格,其實就是向行中添加子視圖。添加子視圖的方法主要有兩種:使用代碼以及從.xib文件加載。固然後一種方法比較直觀。
咱們此次要自定義一個Cell,使得它像QQ好友列表的一行同樣:左邊是一張圖片,圖片的右邊是三行標籤:
固然,咱們不會搞得這麼複雜,只是有點意思就行。
一、運行Xcode 4.2,新建一個Single View Application,名稱爲Custom Cell:
二、將圖片資源導入到工程。爲此,我找了14張50×50的.png圖片,名稱依次是一、二、……、14,放在一個名爲Images的文件夾中。將此文件夾拖到工程中,在彈出的窗口中選中Copy items into…
添加完成後,工程目錄以下:
三、建立一個UITableViewCell的子類:選中Custom Cell目錄,依次選擇File — New — New File,在彈出的窗口,左邊選擇Cocoa Touch,右邊選擇Objective-C class:
單擊Next,輸入類名CustomCell,Subclass of選擇UITableViewCell:
以後選擇Next和Create,就創建了兩個文件:CustomCell.h和CustomCell.m。
四、建立CustomCell.xib:依次選擇File — New — New File,在彈出的窗口,左邊選擇User Interface,右邊選擇Empty:
單擊Next,選擇iPhone,再單擊Next,輸入名稱爲CustomCell,選擇好位置:
單擊Create,這樣就建立了CustomCell.xib。
五、打開CustomCell.xib,拖一個Table View Cell控件到面板上:
選中新加的控件,打開Identity Inspector,選擇Class爲CustomCell;而後打開Size Inspector,調整高度爲60。
六、向新加的Table View Cell添加控件:拖放一個ImageView控件到左邊,並設置大小爲50×50。而後在ImageView右邊添加三個Label,設置標籤字號,最上邊的是14,其他兩個是12:
接下來向CustomCell.h添加Outlet映射,將ImageView與三個Label創建映射,名稱分別爲imageView、nameLabel、decLabel以及locLable,分別表示頭像、暱稱、個性簽名,地點。
選中Table View Cell,打開Attribute Inspector,將Identifier設置爲CustomCellIdentifier:
爲了充分使用這些標籤,還要本身建立一些數據,存在plist文件中,後邊會作。
七、打開CustomCell.h,添加屬性:
@property (copy, nonatomic) UIImage *image; @property (copy, nonatomic) NSString *name; @property (copy, nonatomic) NSString *dec; @property (copy, nonatomic) NSString *loc;
八、打開CustomCell.m,向其中添加代碼:
8.1 在@implementation下面添加代碼:
@synthesize image; @synthesize name; @synthesize dec; @synthesize loc;
8.2 在@end以前添加代碼:
- (void)setImage:(UIImage *)img { if (![img isEqual:image]) { image = [img copy]; self.imageView.image = image; } } -(void)setName:(NSString *)n { if (![n isEqualToString:name]) { name = [n copy]; self.nameLabel.text = name; } } -(void)setDec:(NSString *)d { if (![d isEqualToString:dec]) { dec = [d copy]; self.decLabel.text = dec; } } -(void)setLoc:(NSString *)l { if (![l isEqualToString:loc]) { loc = [l copy]; self.locLabel.text = loc; } }
這至關於重寫了各個set函數,從而當執行賦值操做時,會執行咱們本身寫的函數。
好了,如今本身定義的Cell已經可使用了。
不過在此以前,咱們先新建一個plist,用於存儲想要顯示的數據。創建plist文件的方法前面的文章有提到。咱們建好一個friendsInfo.plist,往其中添加數據以下:
注意每一個節點類型選擇。
九、打開ViewController.xib,拖一個Table View到視圖上,並將Delegate和DataSource都指向File’ Owner,就像上一篇文章介紹的同樣。
十、打開ViewController.h,向其中添加代碼:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource> @property (strong, nonatomic) NSArray *dataList; @property (strong, nonatomic) NSArray *imageList; @end
十一、打開ViewController.m,添加代碼:
11.1 在首部添加:
#import "CustomCell.h"
11.2 在@implementation後面添加代碼:
@synthesize dataList; @synthesize imageList;
11.3 在viewDidLoad方法中添加代碼:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //加載plist文件的數據和圖片 NSBundle *bundle = [NSBundle mainBundle]; NSURL *plistURL = [bundle URLForResource:@"friendsInfo" withExtension:@"plist"]; NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:plistURL]; NSMutableArray *tmpDataArray = [[NSMutableArray alloc] init]; NSMutableArray *tmpImageArray = [[NSMutableArray alloc] init]; for (int i=0; i<[dictionary count]; i++) { NSString *key = [[NSString alloc] initWithFormat:@"%i", i+1]; NSDictionary *tmpDic = [dictionary objectForKey:key]; [tmpDataArray addObject:tmpDic]; NSString *imageUrl = [[NSString alloc] initWithFormat:@"%i.png", i+1]; UIImage *image = [UIImage imageNamed:imageUrl]; [tmpImageArray addObject:image]; } self.dataList = [tmpDataArray copy]; self.imageList = [tmpImageArray copy]; }
11.4 在ViewDidUnload方法中添加代碼:
self.dataList = nil; self.imageList = nil;
11.5 在@end以前添加代碼:
#pragma mark - #pragma mark Table Data Source Methods - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.dataList count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CustomCellIdentifier = @"CustomCellIdentifier"; static BOOL nibsRegistered = NO; if (!nibsRegistered) { UINib *nib = [UINib nibWithNibName:@"CustomCell" bundle:nil]; [tableView registerNib:nib forCellReuseIdentifier:CustomCellIdentifier]; nibsRegistered = YES; } CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier]; NSUInteger row = [indexPath row]; NSDictionary *rowData = [self.dataList objectAtIndex:row]; cell.name = [rowData objectForKey:@"name"]; cell.dec = [rowData objectForKey:@"dec"]; cell.loc = [rowData objectForKey:@"loc"]; cell.image = [imageList objectAtIndex:row]; return cell; } #pragma mark Table Delegate Methods - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 60.0; } - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath { return nil; }
十二、運行:
第三部分:增強理解
看TableView的資料其實已經蠻久了,一直想寫點兒東西,卻老是由於各類緣由拖延,今天晚上有時間靜下心來記錄一些最近學習的TableView的知識。下面進入正題,UITableView堪稱UIKit裏面最複雜的一個控件了,使用起來不算難,可是要用好並不容易。當使用的時候咱們必需要考慮到後臺數據的設計,tableViewCell的設計和重用以及tableView的效率等問題。
下面分9個方面進行介紹:
1、UITableView概述
UITableView繼承自UIScrollView,能夠表現爲Plain和Grouped兩種風格,分別以下圖所示:
其中左邊的是Plain風格的,右邊的是Grouped風格,這個區別仍是很明顯的。
查看UITableView的幫助文檔咱們會注意到UITableView有兩個Delegate分別爲:dataSource和delegate。
dataSource是UITableViewDataSource類型,主要爲UITableView提供顯示用的數據(UITableViewCell),指定UITableViewCell支持的編輯操做類型(insert,delete和reordering),並根據用戶的操做進行相應的數據更新操做,若是數據沒有更具操做進行正確的更新,可能會致使顯示異常,甚至crush。
delegate是UITableViewDelegate類型,主要提供一些可選的方法,用來控制tableView的選擇、指定section的頭和尾的顯示以及協助完成cell的刪除和排序等功能。
提到UITableView,就必須的說一說NSIndexPath。UITableView聲明瞭一個NSIndexPath的類別,主要用來標識當前cell的在tableView中的位置,該類別有section和row兩個屬性,前者標識當前cell處於第幾個section中,後者表明在該section中的第幾行。
UITableView只能有一列數據(cell),且只支持縱向滑動,當建立好的tablView第一次顯示的時候,咱們須要調用其reloadData方法,強制刷新一次,從而使tableView的數據更新到最新狀態。
2、UITableViewController簡介
UITableViewController是系統提供的一個便利類,主要是爲了方便咱們使用UITableView,該類生成的時候就將自身設置成了其包含的tableView的dataSource和delegate,並建立了不少代理函數的框架,爲咱們大大的節省了時間,咱們能夠經過其tableView屬性獲取該controller內部維護的tableView對象。默認狀況下使用UITableViewController建立的tableView是充滿全屏的,若是須要用到tableView是不充滿全屏的話,咱們應該使用UIViewController本身建立和維護tableView。
UITableViewController提供一個初始化函數initWithStyle:,根據須要咱們能夠建立Plain或者Grouped類型的tableView,當咱們使用其從UIViewController繼承來的init初始化函數的時候,默認將會咱們建立一個Plain類型的tableView。
UITableViewController默認的會在viewWillAppear的時候,清空全部選中cell,咱們能夠經過設置self.clearsSelectionOnViewWillAppear = NO,來禁用該功能,並在viewDidAppear中調用UIScrollView的flashScrollIndicators方法讓滾動條閃動一次,從而提示用戶該控件是能夠滑動的。
3、UITableViewCell介紹
UITableView中顯示的每個單元都是一個UITableViewCell對象,看文檔的話咱們會發現其初始化函數initWithStyle:reuseIdentifier:比較特別,跟咱們平時看到的UIView的初始化函數不一樣。這個主要是爲了效率考慮,由於在tableView快速滑動的滑動的過程當中,頻繁的alloc對象是比較費時的,因而引入了cell的重用機制,這個也是咱們在dataSource中要重點注意的地方,用好重用機制會讓咱們的tableView滑動起來更加流暢。
咱們能夠經過cell的selectionStyle屬性指定cell選中時的顯示風格,以及經過accessoryType來指定cell右邊的顯示的內容,或者直接指定accessoryView來定製右邊顯示的view。
系統提供的UITableView也包含了四種風格的佈局,分別是:
typedef enum { UITableViewCellStyleDefault, UITableViewCellStyleValue1, UITableViewCellStyleValue2, UITableViewCellStyleSubtitle } UITableViewCellStyle;
這幾種文檔中都有詳細描述,這兒就不在累贅。然而能夠想象系統提供的只是最經常使用的幾種類型,當系統提供的風格不符合咱們須要的時候,咱們就須要對cell進行定製了,有如下兩種定製方式可選:
1、直接向cell的contentView上面添加subView
這是比較簡單的一種的,根據佈局須要咱們能夠在不一樣的位置添加subView。可是此處須要注意:全部添加的subView都最好設置爲不透明的,由於若是subView是半透明的話,view圖層的疊加將會花費必定的時間,這會嚴重影響到效率。同時若是每一個cell上面添加的subView個數過多的話(一般超過3,4個),效率也會受到比較大的影響。
下面咱們看一個例子:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSArray *sections = [SvTableViewDataModal sections]; SvSectionModal *sectionModal = [sections objectAtIndex:indexPath.section]; static NSString *reuseIdetify = @"SvTableViewCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdetify]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdetify]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; cell.showsReorderControl = YES; for (int i = 0; i < 6; ++i) { UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100 + 15 * i, 0, 30, 20)]; label.backgroundColor = [UIColor redColor]; label.text = [NSString stringWithFormat:@"%d", i]; [cell.contentView addSubview:label]; [label release]; } } cell.textLabel.backgroundColor = [UIColor clearColor]; cell.textLabel.text = [sectionModal.cityNames objectAtIndex:indexPath.row]; return cell; }
在上面這個例子中,我往每一個cell中添加了6個subView,並且每一個subView都是半透明(UIView默認是半透明的),這個時候滑動起來明顯就能夠感受到有點顫抖,不是很流暢。當把每個subView的opaque屬性設置成YES的時候,滑動會比以前流暢一些,不過仍是有點兒卡。
2、從UITableViewCell派生一個類
經過從UITableViewCell中派生一個類,能夠更深度的定製一個cell,能夠指定cell在進入edit模式的時候如何相應等等。最簡單的實現方式就是將全部要繪製的內容放到一個定製的subView中,而且重載該subView的drawRect方法直接把要顯示的內容繪製出來(這樣能夠避免subView過多致使的性能瓶頸),最後再將該subView添加到cell派生類中的contentView中便可。可是這樣定製的cell須要注意在數據改變的時候,經過手動調用該subView的setNeedDisplay方法來刷新界面,這個例子能夠在蘋果的幫助文檔中的TableViewSuite工程中找到,這兒就不舉例了。
觀看這兩種定製cell的方法,咱們會發現subView都是添加在cell的contentView上面的,而不是直接加到cell上面,這樣寫也是有緣由的。下面咱們看一下cell在正常狀態下和編輯狀態下的構成圖:
cell在正常狀態下的構成圖以下:
進入編輯狀態下cell的構成圖以下:
經過觀察上面兩幅圖片咱們能夠看出來,當cell在進入編輯狀態的時候,contentView會自動的縮放來給Editing control騰出位置。這也就是說若是咱們把subView添加到contentView上,若是設置autoresizingMask爲更具父view自動縮放的話,cell默認的機制會幫咱們處理進入編輯狀態的狀況。並且在tableView是Grouped樣式的時候,會爲cell設置一個背景色,若是咱們直接添加在cell上面的話,就須要本身考慮到這個背景色的顯示問題,若是添加到contentView上,則能夠經過view的疊加幫助咱們完成該任務。綜上,subView最好仍是添加到cell的contentView中。
4、Reordering
爲了使UITableVeiew進入edit模式之後,若是該cell支持reordering的話,reordering控件就會臨時的把accessaryView覆蓋掉。爲了顯示reordering控件,咱們必須將cell的showsReorderControl屬性設置成YES,同時實現dataSource中的tableView:moveRowAtIndexPath:toIndexPath:方法。咱們還能夠同時經過實現dataSource中的 tableView:canMoveRowAtIndexPath:返回NO,來禁用某一些cell的reordering功能。
下面看蘋果官方的一個reordering流程圖:
上圖中當tableView進入到edit模式的時候,tableView會去對當前可見的cell逐個調用dataSource的tableView:canMoveRowAtIndexPath:方法(此處官方給出的流程圖有點兒問題),決定當前cell是否顯示reoedering控件,當開始進入拖動cell進行拖動的時候,每滑動過一個cell的時候,會去掉用delegate的tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:方法,去判斷當前劃過的cell位置是否能夠被替換,若是不行則給出建議的位置。當用戶放手時本次reordering操做結束,調用dataSource中的tableView:moveRowAtIndexPath:toIndexPath:方法更新tableView對應的數據。
此處給個我寫demo中的更新數據的小例子:
// if you want show reordering control, you must implement moveRowAtndexPath, or the reordering control will not show // when use reordering end, this method is invoke - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath { // update DataModal NSArray *sections = [SvTableViewDataModal sections]; SvSectionModal *sourceSectionModal = [sections objectAtIndex:sourceIndexPath.section]; NSString *city = [[sourceSectionModal.cityNames objectAtIndex:sourceIndexPath.row] retain]; [sourceSectionModal.cityNames removeObject:city]; [SvTableViewDataModal replaceSectionAtIndex:sourceIndexPath.section withSection:sourceSectionModal]; SvSectionModal *desinationsSectionModal= [[SvTableViewDataModal sections] objectAtIndex:destinationIndexPath.section]; [desinationsSectionModal.cityNames insertObject:city atIndex:destinationIndexPath.row]; [SvTableViewDataModal replaceSectionAtIndex:destinationIndexPath.section withSection:desinationsSectionModal]; [city release]; }
上面代碼中首先拿到源cell所處的section,而後從該section對應的數據中移除,而後拿到目標section的數據,而後將源cell的數據添加到目標section中,並更新回數據模型,若是咱們沒有正確更新數據模型的話,顯示的內容將會出現異常。
5、Delete & Insert
cell的delete和insert操做大部分流程都是同樣的,當進入編輯模式的時候具體的顯示是delete仍是insert
取決與該cell的editingStyle的值,editStyle的定義以下:
typedef enum { UITableViewCellEditingStyleNone, UITableViewCellEditingStyleDelete, UITableViewCellEditingStyleInsert } UITableViewCellEditingStyle;
當tableView進入編輯模式之後,cell上面顯示的delete仍是insert除了跟cell的editStyle有關,還與 tableView的delegate的tableView:editingStyleForRowAtIndexPath:方法的返回值有關(在這裏嘮叨一句,其實delegate提供了不少改變cell屬性的機會,如非必要,仍是不要去實現這些方法,由於執行這些方法也形成必定的開銷)。
delete和insert的流程以下蘋果官方文檔中給出的圖所示:
下面是我寫的demo中刪除和添加部分的代碼:
#pragma mark - - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"commit editStyle: %d", editingStyle); if (editingStyle == UITableViewCellEditingStyleDelete) { NSArray *sections = [SvTableViewDataModal sections]; SvSectionModal *sourceSectionModal = [sections objectAtIndex:indexPath.section]; [sourceSectionModal.cityNames removeObjectAtIndex:indexPath.row]; [SvTableViewDataModal replaceSectionAtIndex:indexPath.section withSection:sourceSectionModal]; [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight]; } else { // do something for add it NSArray *sections = [SvTableViewDataModal sections]; SvSectionModal *sourceSectionModal = [sections objectAtIndex:indexPath.section]; [sourceSectionModal.cityNames insertObject:@"new City" atIndex:indexPath.row]; [SvTableViewDataModal replaceSectionAtIndex:indexPath.section withSection:sourceSectionModal]; [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight]; } }
代碼中首先判斷當前操做是delete操做仍是insert操做,相應的更新數據,最後根據狀況調用tableView的insertRowsAtIndexPaths:withRowAnimation:或者deleteRowsAtIndexPaths:withRowAnimation:方法,對tableView的視圖進行更新。cell的刪除和添加操做相對仍是比較簡單的。
6、Cell的Select操做
當咱們在tableView中點擊一個cell的時候,將會調用tableView的delegate中的tableView:didSelectRowAtIndexPath:方法。
關於tableView的cell的選中,蘋果官方有如下幾個建議:
1、不要使用selection來代表cell的選擇狀態,而應該使用accessaryView中的checkMark或者自定義accessaryView來顯示選中狀態。
2、當選中一個cell的時候,你應該取消前一個cell的選中。
3、若是cell選中的時候,進入下一級viewCOntroller,你應該在該級菜單從navigationStack上彈出的時候,取消該cell的選中。
這塊兒再提一點,當一個cell的accessaryType爲UITableViewCellAccessoryDisclosureIndicator的時候,點擊該accessary區域一般會將消息繼續向下傳遞,即跟點擊cell的其餘區域同樣,將會掉delegate的tableView:didSelectRowAtIndexPath:方法,當時若是accessaryView爲 UITableViewCellAccessoryDetailDisclosureButton的時候,點擊accessaryView將會調用delegate的 tableView:accessoryButtonTappedForRowWithIndexPath:方法。
7、批量插入,刪除,部分更新操做
UITableView提供了一個批量操做的特性,這個功能在一次進行多個row或者scetion的刪除,插入,獲取更新多個cell內容的時候特別好用。全部的批量操做須要包含在beginUpdates和endUpdates塊中,不然會出現異常。
下面請看我demo中的一個批量操做的例子:
- (void)groupEdit:(UIBarButtonItem*)sender { [_tableView beginUpdates]; // first update the data modal [_tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationTop]; [_tableView deleteSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationTop]; [SvTableViewDataModal deleteSectionAtIndex:0]; SvSectionModal *section = [[SvTableViewDataModal sections] objectAtIndex:0]; [section.cityNames insertObject:@"帝都" atIndex:0]; [SvTableViewDataModal replaceSectionAtIndex:0 withSection:section]; [_tableView endUpdates]; }
上面的例子中咱們能夠看到先往tableView的第0個section的第0行添加一個cell,而後將第0個section刪掉。按照咱們程序中寫的順序,那麼新添加進去的「帝都」,將不在會顯示,由於包含它的整個section都已經被刪除了。
執行程序先後結果以下圖:
demo中第0個section是陝西省的城市,第1個section是北京。左邊是執行前的截圖,右邊是執行後的截圖,觀察發現結果並不像咱們前面推測的那樣。那是由於在批量操做時,無論代碼中先寫的添加操做仍是刪除操做,添加操做都會被推出執行,直到這個塊中全部的刪除操做都執行完之後,纔會執行添加操做,這也就是上面蘋果官方圖片上要表達的意思。
蘋果官方文檔有一副圖能夠幫助咱們更好的理解這一點:
原圖中操做是:首先刪除section 0中的row 1,而後刪除section 1,再向section 1中添加一行。執行完批量更新之後就獲得右半邊的結果。
8、IndexList
當咱們tableView中section有不少,數據量比較大的時候咱們能夠引入indexList,來方便完成section的定位,例如系統的通信錄程序。咱們能夠經過設置tableView的sectionIndexMinimumDisplayRowCount屬性來指定當tableView中多少行的時候開始顯示IndexList,默認的設置是NSIntegerMax,即默認是不顯示indexList的。
爲了可以使用indexlist咱們還須要實現dataSource中一下兩個方法:
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index;
第一個方法返回用於顯示在indexList中的內容的數組,一般爲A,B,C...Z。第二個方法的主要做用是根據用戶在indexList中點擊的位置,返回相應的section的index值。這個例子能夠在蘋果官方給出的TableViewSuite中找到,實現起來仍是很簡單的。
9、其餘
1、分割線
咱們能夠經過設置tableView的separatorStyle屬性來設置有無分割線以及分割線的風格,其中style定義以下:
typedef enum { UITableViewCellSeparatorStyleNone, UITableViewCellSeparatorStyleSingleLine, UITableViewCellSeparatorStyleSingleLineEtched } UITableViewCellSeparatorStyle;
同時還能夠經過tableView的separatorColor屬性來設置分割線的顏色。
2、如何提升tableView的性能
a、重用cell
咱們都知道申請內存是須要時間,特別是在一段時間內頻繁的申請內存將會形成很大的開銷,並且上tebleView中cell大部分狀況下佈局都是同樣的,這個時候咱們能夠經過回收重用機制來提升性能。
b、避免content的從新佈局
儘可能避免在重用cell時候,對cell的從新佈局,通常狀況在在建立cell的時候就將cell佈局好。
c、使用不透明的subView
在定製cell的時候,將要添加的subView設置成不透明的會大大減小多個view層疊加時渲染所須要的時間。
d、若是方便,直接重載subView的drawRect方法
若是定製cell的過程當中須要多個小的元素的話,最好直接對要顯示的多個項目進行繪製,而不是採用添加多個subView。
e、tableView的delegate的方法如非必要,儘可能不要實現
tableView的delegate中的不少函數提供了對cell屬性的進一步控制,好比每一個cell的高度,cell是否能夠編輯,支持的edit風格等,如非必要最好不要實現這些方法由於快速的調用這些方法也會影響性能。
(以上5點建議,前三點來自蘋果官方文檔,後兩點我本身加的,有什麼不對的地方,歡迎指正)
小結:UITableView自己是很複雜的,本片博客只起到拋磚引玉的做用,歡迎你們補充。想用好UITableView,仍是須要實際項目中的鍛鍊的