首先、對UITableView進行講解,下面有對它進行實際的應用數組
UITableView app
顯示大型內容的列表框架
TableView Stylesiphone
UITableView有兩個默認的內置風格,ide
表格視圖以及組成部分函數
使用TableViews性能
在表格視圖中顯示數據ui
定製顯示的外觀和行爲atom
一個直接的解決方法spa
表格視圖用來顯示一列數據,因此使用一個數組
[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; }
十二、運行: