從零開始學ios開發(十二):Table Views(上)

來源:互聯網
上載者:User

這次學習的控制項非常重要且非常強大,是ios應用中使用率非常高的一個控制項,可以說幾乎每個app都會使用到它,它就是功能異常強大的Table Views。可以開啟你的iphone中的phone、Messages、Contacts、Mail、Settings等等等等,這些都用到了Table Views。

在Table Views中,Table是用來顯示一系列資料的,每條資料佔用且只佔用一行(一個table cell),在ios中沒有規定table到底可以容納多少行資料,也就是說,只要記憶體足夠多,table可以容納任意多行的資料。

上面的2段文字,一共提到了三個概念:Table,Table View Cell,Table View,它們之間的關係如下,Table用來儲存資料,Table View用來顯示當前可見的Table中的資料(也就是iphone螢幕中顯示的那些資料),Table View Cell就是當前可見的Table View中的那一行,這樣說可能還不是最清楚,那麼看下面的圖,你就可以有一個比較直觀的認識了。

ios的設計是很注重資源的節省的,這樣做的好處就是能夠是程式啟動並執行儘可能的快,給使用者更好的體驗,因此一些不需要的東西,ios是堅決不會顯示或者產生的,在Table Views中,只有當前瀏覽到的資料,會產生table view cell,然後顯示,沒有瀏覽到的資料,不會產生多餘的cell,而且當一個cell移除螢幕後,這個cell會給進入螢幕的資料繼續使用,因此,產生的cell的數量會是固定的,不會多不會少,正好夠在table view中顯示。

和前一篇Pickers一樣,Table Views也使用delegate:UITableViewDelegate,UITableViewDataSource。

另外,Table Views只有一列,每行只有一個cell,每個cell可以包含一張圖片,一些文字,一個icon,任意多個subview(之後都會有例子,看了就明白了)。

好了,說了一些概念性的東西,還是有點小小的枯燥,下面開始coding。

1)建立一個新的項目,這次選擇Single View Application模板,命名為Simple Table

2)添加Table View控制項 在Project navigator中選中BIDViewController.xib,在Object Library中找到上面的Table View控制項,拖到view上面,Table View將佔滿整個view(一般來所,Table View會佔滿整個view,當然必要時會空出navigator bar,tool bar,tab bar)

選中view中的table view,開啟Connections Inspector,會看到很熟悉的dataSource和delegate,這個在學習Picker View的時候已經見到過,這裡的作用和在Picker View中是一樣的。將它們關聯到File's Owner

3)寫code 開啟BIDViewController.h,添加如下代碼

#import <UIKit/UIKit.h>@interface BIDViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>@property (strong, nonatomic) NSArray *listData;@end

有沒有很熟悉的感覺,Table View的協議(protocols)和Picker View的是一樣的,然後聲明一個NSArray來存放資料。

開啟BIDViewController.m,添加如下代碼

#import "BIDViewController.h"@implementation BIDViewController@synthesize listData;- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Release any cached data, images, etc that aren't in use.}#pragma mark - View lifecycle- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    NSArray *array = [[NSArray alloc] initWithObjects:@"Sleepy", @"Sneezy",                      @"Bashful", @"Happy", @"Doc", @"Grumpy", @"Dopey", @"Thorin",                      @"Dorin", @"Nori", @"Ori", @"Balin", @"Dwalin", @"Fili", @"Kili",                      @"Oin", @"Gloin", @"Bifur", @"Bofur", @"Bombur", nil];    self.listData = array;}- (void)viewDidUnload{    [super viewDidUnload];    // Release any retained subviews of the main view.    // e.g. self.myOutlet = nil;    self.listData = nil;}#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 = @"SimlpeTableIdentifier";        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];    if(cell == nil) {        cell = [[UITableViewCell alloc]                initWithStyle:UITableViewCellStyleDefault                reuseIdentifier:SimpleTableIdentifier];    }        NSUInteger row = [indexPath row];    cell.textLabel.text = [listData objectAtIndex:row];        return cell;}
......

這裡面需要解釋的就是2個dataSource方法,其他的方法都簡單,在這裡就不過多解釋了: tableView:numberOfRowsInSection:用來告訴table view在Section中有多少個資料(listData中的資料個數),這裡有一個Section的概念,暫且先不用理會,我們這個例子中只有1個Section,因此直接返回listData中的資料個數即可(Section的概念下一篇會介紹) tableView:cellForRowAtIndexPath:當table view需要建立一個cell時,會調用該方法。這個方法稍微有點複雜,但也不是很難理解,首先聲明了一個靜態字串SimpleTableIdentifier,這個字串作為一個key用來標識UITableViewCell的類型,凡是cell擁有這個key,就可以認為他們是同一種類型的cell,相互之間可以任意使用。前面已經說過,一個Table View在同一時間只會建立一定數量的Table View Cell(夠用就好),因此當一個cell移出螢幕後,這個cell會被放入一個隊列,等待其他即將顯示的資料使用。接下來的一句語句 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier]; 就是通過剛才的key來尋找可重複使用的Table View Cell。 如果沒有可重複使用的cell(cell == nil),那麼就需要建立一個新的cell cell = [[UITableViewCell alloc]   initWithStyle:UITableViewCellStyleDefault //設定cell顯示的樣式   reuseIdentifier:SimpleTableIdentifier]; //設定標示符SimpleTableIdentifier(設定key),這樣以後這個cell才可以被制定的key找到並重複使用。 cell建立完成後,需要設定顯示的文字 NSUInteger row = [indexPath row]; //通過indexPath找到現在顯示第幾行的資料 cell.textLabel.text = [listData objectAtIndex:row]; //得到行號後再去listData中找到相應的資料,並複製給cell的屬性textLabel。 這些都設定好後,返回cell即可

4)編譯運行 希望上面的解釋大家都能夠看懂,然後command+B,command+R編譯運行程式,效果如下

5)添加圖片 可以為每個cell添加一張圖片,並顯示在cell的左邊,首先下載下面的圖片:Star.png 然後將圖片拖到Project navigator中,放在Simple Table檔案夾下 開啟BIDViewController.m,在剛才添加的tableView:cellForRowAtIndexPath方法中添加如下代碼

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    static NSString *SimpleTableIdentifier = @"SimlpeTableIdentifier";        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];    if(cell == nil) {        cell = [[UITableViewCell alloc]                initWithStyle:UITableViewCellStyleDefault                reuseIdentifier:SimpleTableIdentifier];    }        UIImage *image = [UIImage imageNamed:@"star.png"];    cell.imageView.image = image;        NSUInteger row = [indexPath row];    cell.textLabel.text = [listData objectAtIndex:row];        return cell;}

好了,在此編譯code並運行,效果如下 很簡單吧,如果當我們選中table view中的一行,想換一張圖片,表示選中的狀態,進行如下操作 添加一張選中狀態的圖片到Simple Table檔案夾下:Star2.png 開啟BIDViewController.m,在tableView:cellForRowAtIndexPath方法中添加如下代碼

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    static NSString *SimpleTableIdentifier = @"SimlpeTableIdentifier";        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];    if(cell == nil) {        cell = [[UITableViewCell alloc]                initWithStyle:UITableViewCellStyleDefault                reuseIdentifier:SimpleTableIdentifier];    }        UIImage *image = [UIImage imageNamed:@"star.png"];    cell.imageView.image = image;        UIImage *image2 = [UIImage imageNamed:@"star2.png"];    cell.imageView.highlightedImage = image2;        NSUInteger row = [indexPath row];    cell.textLabel.text = [listData objectAtIndex:row];        return cell;}

編譯運行,效果如下 當我們選中一行row的時候,圖片發生了變化,UITableViewCell的屬性imageView.image用來設定一般狀態下的圖片,imageView.highlightedImage用來設定選中狀態下的圖片,如果不設定,將繼續使用一般狀態下的圖片。

6)UITableViewCell的Style 在介紹style之前,先看看UITableViewCell內建的3個屬性,其中2個我們在之前的例子中已經使用到,分別是TextLabel和imageView,第三個屬性是detailTextLabel,看下面的例子,就知道這個detailTextLabel是什麼東東了,還是開啟BIDViewController.m,在tableView:cellForRowAtIndexPath方法中添加如下代碼

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    static NSString *SimpleTableIdentifier = @"SimlpeTableIdentifier";        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];    if(cell == nil) {        cell = [[UITableViewCell alloc]                initWithStyle:UITableViewCellStyleDefault                reuseIdentifier:SimpleTableIdentifier];    }        UIImage *image = [UIImage imageNamed:@"star.png"];    cell.imageView.image = image;        UIImage *image2 = [UIImage imageNamed:@"star2.png"];    cell.imageView.highlightedImage = image2;        NSUInteger row = [indexPath row];    cell.textLabel.text = [listData objectAtIndex:row];        if (row < 7)         cell.detailTextLabel.text = @"Mr. Disney";    else         cell.detailTextLabel.text = @"Mr. Tolkien";        return cell;}

編譯運行 有沒有發現什麼變化也沒有?這是因為是用來UITableViewCellStyleDefault樣式造成的,UITableViewCell一共有4種樣式,在tableView:cellForRowAtIndexPath方法中,建立cell的時候設定initWithStyle,就是cell的樣式。

cell = [[UITableViewCell alloc]                initWithStyle:UITableViewCellStyleDefault                reuseIdentifier:SimpleTableIdentifier];

現在換一種樣式看看,將上面代碼中的UITableViewCellStyleDefault改成UITableViewCellStyleSubtitle,在編譯運行看一下效果 這次效果對了,所有的3個屬性都顯示出來了。

總結一下所有4個UITableViewCell的樣式 UITableViewCellStyleDefault

UITableViewCellStyleSubtitle

UITableViewCellStyleValue1

UITableViewCellStyleValue2

最後別忘了還是將樣式設定回UITableViewCellStyleDefault,之後的例子還是以這個樣式為例子的

7)UITableViewCell的縮排 開啟BIDViewController.m,添加如下代碼

#pragma mark -#pragma mark Table Delegate Methods- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {    NSUInteger row = [indexPath row];    return row;}

tableview:indentationLevelForRowAtIndexPath這個方法用於設定縮排的層級,使用indexPath取得當前row是在第幾行,然後根據第幾行來設定縮排的大小。注意,這個方法是table view的delegate方法,之前用到的方法都是dataSource方法。

編譯運行

8)UITableViewCell的選擇事件 UITableViewCell的選擇事件有2種,一種在選中一行之前發生的事件,叫做tableView:willSelectRowAtIndexPath,另一個方法就是選中一行後發生的事件,叫做tableView:didSelectRowAtIndexPath,他們都是table view的delegate方法,在BIDViewController.m中添加如下code

- (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];}

在tableView:willSelectRowAtIndexPath中,根據indexPath來獲得即將選中的是哪一行,然後判斷如果即將選中的row是第一行,則返回nil,使其無法選中,如果不是,則返回indexPath。

在tableView:didSelectRowAtIndexPath中,根據indexPath來獲得選中的是哪一行,然後讀取這一行的資料(其實是根據行號到NSArray中找到相應的資料),然後顯示出來。

編譯運行,試著選擇第一行,是不會有反應的,然後選擇其他行,一個警告框會彈出

9)更改UITableViewCell的字型大小和行的高度 還是在tableView:cellForRowAtIndexPath中,添加如下代碼

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    static NSString *SimpleTableIdentifier = @"SimlpeTableIdentifier";        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];    if(cell == nil) {        cell = [[UITableViewCell alloc]                initWithStyle:UITableViewCellStyleDefault                reuseIdentifier:SimpleTableIdentifier];    }        UIImage *image = [UIImage imageNamed:@"star.png"];    cell.imageView.image = image;        UIImage *image2 = [UIImage imageNamed:@"star2.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. Tolkien";        return cell;}

將字型的大小設定成50,編譯運行 字型是變大了,但是行高太小,以至於字元無法顯示完整,我們需要調整行高,添加一個新的table view的delegate,如下

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {    return 70;}

tableView:heightForRowAtIndexPath用來設定行高,因為是將這個table view的行高進行統一設定,所以直接返回高度即可,如果需要針對某些行進行調整,那麼就需要通過indexPath來獲得第幾行,然後在進行行高的設定

編譯運行

ok,現在和諧了。

10)總結 這篇是Table View的入門學習,學習了Table View中最最基礎的一些東西,讀取顯示資料,添加圖片,cell的樣式,縮排,字型大小,行高等等的一些基礎內容,後一篇的內容會講到自訂Table View Cell的內容,難度有所加深,但總得來說還是很簡單的。反正IOS學習到現在,給我的感覺似乎是越來越容易,很多東西開始變得容易上手了,很多概念都是融會貫通的,大家繼續努力加油啊,謝謝大家的一直關注,我也會繼續努力的,謝謝!

 

Simple Table

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.