首先、對UITableView進行講解,下面有對它進行實際的應用
UITableView
TableView Styles
表格視圖以及組成部分
使用TableViews
在表格視圖中顯示數據
定製顯示的外觀和行爲
一個直接的解決方法
表格視圖用來顯示一列數據,所以使用一個數組
[myTableView setList : myListOfStuff];//該方法不存在,想法比較天真
該方法爭議性
所有的數據必須事先裝載
所有的數據都裝載在內存中
更加靈活的方案
另外一個對象爲表格視圖提供數據
不是一次性全部取得
只取現在需要展示的數據
像一個委託,它是純粹的數據導向,它只向數據源詢問數據
UITableViewDataSource(數據源協議)
提供章節和行的數目
//optionalmethod ,default to 1 if not implemented
-(NSInteger)numberOfSectionsInTableV
//requiredmethod
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
必要的時候向表格視圖提供所要顯示的cells
//required method
NSIndexPath
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
}
單元複用(cellreuse)
UITableViewCell*cell
= [tableViewdequeueReusableCellWithI
if(cell==
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
-(void)ideleteSections:(NSIndexSet*)sectionswithRowAnimation
-(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;
其它的數據源方法
允許編輯和重排單元
外觀和行爲
可定製外觀和行爲
邏輯獨立於視圖
數據源和委派經常是相同的對象(事實上,很少情況下數據源不是委派)
驗證和響應所選擇的變化
使用表格視圖委派功能,對於選擇會有不同的功能
-(NSIndexPath*)tableView:(UITableView
*)tableViewwillSelectRowAt
-(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.navigationControllerpush
}
修改和禁用選擇
-(NSIndexPath*)tableView:(UITableView
*)tableViewwillSelectRowAt
if(indexPath.row== ….) {
returnnil;
}
else{ return indexPath ;}
}
UITableViewController
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”;
效果如圖:
附件類型
//UITableView委託方法
-(UITableViewCellAccessory
-(void)tableView:(UITableView
*)tableViewaccessoryButton
//只有是在藍色描述的按鈕(也就是上面的第二個)
NSIntegerrow = indexPath.row.
}
定製內容視圖
在有些情況下,簡單的圖像和文本是不夠的
UITableViewCell有一個contentview
爲contentview
-(UITableViewCell*)
tableView :(UITableView) tableViewcellForRowAtInd
UITableViewCell*cell = ….......;
CGRectframe = cell.contentView.bounds;
UILabel*myLabel = [[UILabel alloc] initWithFrame :frame];
myLabel.text= ….;
[cell.contentViewaddSubview : myLabel];
[myLabelrelease];
}
其次,實際的使用方法
第一種,正常的使用方法
//
//
//
//
//
//
//
#import
@implementation
- (void)dealloc
{
}
- (void)didReceiveMemoryWarning
{
}
#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
}
-(void)edit:(id)sender
{
}
#pragma mark TableView Delegate
//對編輯的狀態下提交的事件響應
-(void)tableView:(UITableView
{
}
//響應選中事件
-(void)tableView:(UITableView
}
//行將顯示的時候調用
-(void)tableView:(UITableView
{
}
//點擊了附加圖標時執行
-(void)tableView:(UITableView
{
}
//開始移動row時執行
-(void)tableView:(UITableView
{
}
//開發可以編輯時執行
-(void)tableView:(UITableView
{
}
//選中之前執行
-(NSIndexPath*)tableView:(UITableView
{
}
//將取消選中時執行
-(NSIndexPath
{
}
//移動row時執行
-(NSIndexPath
{
}
//刪除按鈕的名字
-(NSString*)tableView:(UITableView
{
}
//讓表格可以修改,滑動可以修改
-(BOOL)tableView:(UITableView
{
}
//讓行可以移動
-(BOOL)tableView:(UITableView
{
}
-(UITableViewCellEditingSt
{
}
#pragma mark TableView DataSource
-(NSInteger)numberOfSectionsInTableV
}
-(NSInteger)tableView:(UITableView
}
-(UITableViewCell
{
}
- (void)viewDidUnload
{
}
- (BOOL)shouldAutorotateToInterf
{
}
@end
第二種,使用自定義UITbaleViewCell方法。
其實很簡單,只需要定義一個UItableViewCell的子類,然後在初始化cell的時候,使用自定義的cell生成cell就可以了。
@interface
}
@end
上篇文章介紹瞭如何用UITableView顯示錶格,並講了幾種UITableViewCell的風格。不過有時候我們需要自己定義 UITableViewCell的風格,其實就是向行中添加子視圖。添加子視圖的方法主要有兩種:使用代碼以及從.xib文件加載。當然後一種方法比較直 觀。
我們這次要自定義一個Cell,使得它像QQ好友列表的一行一樣:左邊是一張圖片,圖片的右邊是三行標籤:
當然,我們不會搞得這麼複雜,只是有點意思就行。
1、運行Xcode 4.2,新建一個Single View Application,名稱爲Custom Cell:
2、將圖片資源導入到工程。爲此,我找了14張50×50的.png圖片,名稱依次是1、2、……、14,放在一個名爲Images的文件夾中。將此文件夾拖到工程中,在彈出的窗口中選中Copy items into…
添加完成後,工程目錄如下:
3、創建一個UITableViewCell的子類:選中Custom Cell目錄,依次選擇File — New — New File,在彈出的窗口,左邊選擇Cocoa Touch,右邊選擇Objective-C class:
單擊Next,輸入類名CustomCell,Subclass of選擇UITableViewCell:
之後選擇Next和Create,就建立了兩個文件:CustomCell.h和CustomCell.m。
4、創建CustomCell.xib:依次選擇File — New — New File,在彈出的窗口,左邊選擇User Interface,右邊選擇Empty:
單擊Next,選擇iPhone,再單擊Next,輸入名稱爲CustomCell,選擇好位置:
單擊Create,這樣就創建了CustomCell.xib。
5、打開CustomCell.xib,拖一個Table View Cell控件到面板上:
選中新加的控件,打開Identity Inspector,選擇Class爲CustomCell;然後打開Size Inspector,調整高度爲60。
6、向新加的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文件中,後邊會做。
7、打開CustomCell.h,添加屬性:
@property (copy, nonatomic) UIImage *image; @property (copy, nonatomic) NSString *name; @property (copy, nonatomic) NSString *dec; @property (copy, nonatomic) NSString *loc;
8、打開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,往其中添加數據如下:
注意每個節點類型選擇。
9、打開ViewController.xib,拖一個Table View到視圖上,並將Delegate和DataSource都指向File’ Owner,就像上一篇文章介紹的一樣。
10、打開ViewController.h,向其中添加代碼:
#import @interface ViewController : UIViewController @property (strong, nonatomic) NSArray *dataList; @property (strong, nonatomic) NSArray *imageList; @end
11、打開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 dictionaryWithContentsOf<wbr>URL: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]; } </wbr>
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 dequeueReusableCellWithI<wbr>dentifier: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<wbr>:(NSIndexPath *)indexPath { return nil; } </wbr></wbr>
12、運行:
更改cell選中的背景