UITableView与UITableViewCell 简单demo

此例子适合于初学者对TableView不了解的朋友,能学到一些知识,不至于毫无头绪。高手绕行。

 

UITableView用来以表格的形式显示数据。关于UITableView,我们应该注意:

(1)UITableView用来显示表格的可见部分,UITableViewCell用来显示表格的一行。

(2)UITableView并不负责存储表格中的数据,而是仅仅存储足够的数据使得可以画出当前可见部分。

(3)UITableView从UITableViewDelegate协议获取配置信息,从UITableViewDataSource协议获得数据信息。

(4)所有的UITableView实现时实际上只有一列,但是我们可以通过向UITableViewCell中添加子视图,使得它看起来有好几列。

(5)UITableView有两种风格:

    ① Grouped:每一组看起来像是圆矩形;
    ② Plain:这是默认风格,可以修改成Indexed风格。
在下边的小例子中,我们将先实现显示一列数据,然后在每行添加图像,之后再看看UITableViewCell的四种分别是什么样的。最后再进行其他操作,比如设置缩进、修改字体大小和行高等。

1、运行Xcode 4.2,新建一个Single View Application,名称为Table Sample:

 

2、单击ViewController.xib,使用Interface Builder给视图添加一个UITableView控件,并使其覆盖整个视图:

 

3、选中新添加的UITableView控件,打开Connection Inspector,找到delegate和datasource,从它们右边的圆圈拉线到File's Owner图标:

 

4、单击ViewController.h,在其中添加代码:

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

 

  

5、单击ViewController.m,在其中添加代码:

5.1 在@implementation后面添加代码:

1 @synthesize listData;

 

5.2 在viewDidLoad方法中添加代码:

1     - (void)viewDidLoad
2     {
3         [super viewDidLoad];
4         // Do any additional setup after loading the view, typically from a nib.
5         NSArray *array = [[NSArray alloc] initWithObjects:@"Tree", @"Flower",
6                           @"Grass", @"Fence", @"House", @"Table", @"Chair",
7                           @"Book", @"Swing" , nil]; 
8         self.listData = array; 
9     }

 

5.3 在viewDidUnload方法中添加代码:

1     - (void)viewDidUnload
2     {
3         [super viewDidUnload];
4         // Release any retained subviews of the main view.
5         // e.g. self.myOutlet = nil;
6         self.listData = nil;
7     }

 

5.4 在@end之前添加代码:

 1  #pragma mark - 
 2     #pragma mark Table View Data Source Methods 
 3     //返回行数
 4     - (NSInteger)tableView:(UITableView *)tableView 
 5      numberOfRowsInSection:(NSInteger)section { 
 6         return [self.listData count]; 
 7     }
 8       
 9     //新建某一行并返回
10     - (UITableViewCell *)tableView:(UITableView *)tableView 
11              cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
12           
13         static NSString *TableSampleIdentifier = @"TableSampleIdentifier"; 
14           
15         UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: 
16                                  TableSampleIdentifier]; 
17         if (cell == nil) { 
18             cell = [[UITableViewCell alloc] 
19                     initWithStyle:UITableViewCellStyleDefault 
20                     reuseIdentifier:TableSampleIdentifier]; 
21         } 
22           
23         NSUInteger row = [indexPath row]; 
24         cell.textLabel.text = [listData objectAtIndex:row]; 
25         return cell;     
26 }

 

上面的第二个方法中,

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: TableSampleIdentifier];

 

这个语句根据标识符TableSampleIdentifier寻找当前可以重用的UITableViewCell。当某行滑出当前可见区域后,我们重用它所对应的UITableViewCell对象,那么就可以节省内存和时间。

如果执行词语后,cell为nil,那我们再创建一个,并设置去标识符为TableSampleIdentifier:

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

这里UITableViewCellStyleDefault是表示UITableViewCell风格的常数,除此之外,还有其他风格,后面将会用到。

注意参数(NSIndexPath *)indexPath,它将行号row和部分号section合并了,通过[indexPath row];获取行号。之后给cell设置其文本:

cell.textLabel.text = [listData objectAtIndex: row];

 

6、运行一下:

 

7、给每一行添加图片:

7.1 将图片资源添加到工程:拖到工程中,前面的文章有提到。

7.2 在cellForRowAtIndexPath方法的return语句之前添加代码

    UIImage *image = [UIImage imageNamed:@"blue.png"]; 
    cell.imageView.image = image; 
    UIImage *highLighedImage = [UIImage imageNamed:@"yellow.png"]; 
    cell.imageView.highlighedImage = highLighedImage;

 

7.3 运行,效果如下:

 

可以看到,每行左边都出现一张图片。当选中某行,其图片改变。

8、设置行的风格:

表示UITableViewCell风格的常量有:

  UITableViewCellStyleDefault
    UITableViewCellStyleSubtle
    UITableViewCellStyleValue1
    UITableViewCellStyleValue2

 

这几种风格的区别主要体现在Image、Text Label以及Detail Text Label。

为了体现风格,在cellForRowAtIndexPath方法的return语句之前添加代码:

cell.detailTextLabel.text = @"Detail Text";

 

然后将
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];

 

中的UITableViewCellStyleDefault依次换成上面提到的四个风格常量,并运行,效果分别如下:

  

            UITableViewCellStyleDefault                                   UITableViewCellStyleSubtle

  

             UITableViewCellStyleValue1                                  UITableViewCellStyleValue2

9、设置缩进:

将所有行的风格改回UITableViewCellStyleDefault,然后在@end之前添加代码如下:

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

 

这里将第row行缩进row,如下图所示:

 

10、操纵行选择:

在@end之前添加代码:

   - (NSIndexPath *)tableView:(UITableView *)tableView 
      willSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
        NSUInteger row = [indexPath row];
        if (row%2 == 0) {
            return nil;
        }
        return indexPath; 
    }

 

上面的方法在选择某行之前执行,我们可以在这个方法中添加我们想要的操作。这里,我们实现的是,如果选择的行号(从0开始计)是偶数,则取消选择。

在@end之前添加代码:

    - (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 deselectRowAtIndexPath:indexPath animated:YES]; 
    }

 

当选择某行之后,就弹出一个Alert,用来显示我们所做的选择。

运行一下,你会发现第0、2等行无法选择。选择奇数行时会弹出提示:

 

而且关闭提示框后,选择的那行也被取消了选择,用的语句

[tableView deselectRowAtIndexPath:indexPath animated:YES];

 

11、设置字体大小和表格行高:

11.1 在cellForRowAtIndexPath方法中的return之前添加代码,用于设置字体和大小:

cell.textLabel.font = [UIFont boldSystemFontOfSize:50];

 

 

11.2 在@end之前添加代码,用于设置行高:

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

运行,看看效果:

 viewController.M全部代码

View Code
  1 //
  2 //  ViewController.m
  3 //  TableSample
  4 //
  5 //  Created by djy dda on 12-7-19.
  6 //  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
  7 //
  8 
  9 #import "ViewController.h"
 10 
 11 @implementation ViewController
 12 
 13 @synthesize listData;
 14 
 15 - (void)didReceiveMemoryWarning
 16 {
 17     [super didReceiveMemoryWarning];
 18     // Release any cached data, images, etc that aren't in use.
 19 }
 20 
 21 
 22 - (id)init{
 23     self = [super init];
 24     if(self !=nil){
 25         ///初始化导航栏按钮
 26         self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(startEditing)];
 27         self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Reload" style:UIBarButtonItemStylePlain target:self action:@selector(reload)];
 28         
 29     }
 30     return self;
 31 }
 32 
 33 #pragma mark - View lifecycle
 34 
 35 - (void)viewDidLoad
 36 {
 37     [super viewDidLoad];
 38     // Do any additional setup after loading the view, typically from a nib.
 39     NSArray *array = [[NSArray alloc] initWithObjects:@"Tree", @"Flower",
 40                                           @"Grass", @"Fence", @"House", @"Table", @"Chair",
 41                                            @"Book", @"Swing" , nil]; 
 42    self.listData = array; 
 43 }
 44 
 45 - (void)viewDidUnload
 46 {
 47     [super viewDidUnload];
 48     // Release any retained subviews of the main view.
 49     // e.g. self.myOutlet = nil;
 50     self.listData = nil;
 51 }
 52 
 53 ///返回总行
 54 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
 55     return [self.listData count];
 56 }
 57 
 58 ///新建某一行并返回
 59 ///注意参数(NSIndexPath *)indexPath,它将行号row和部分号section合并了,通过[indexPath row];获取行号。之后给cell设置其文本
 60 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 61     
 62     static NSString *TableSampleIdentifier = @"TableSampleIdentifier";
 63     
 64     //这个语句根据标识符TableSampleIdentifier寻找当前可以重用的UITableViewCell。当某行滑出当前可见区域后,我们重用它所对应的UITableViewCell对象,那么就可以节省内存和时间。
 65     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableSampleIdentifier];
 66     
 67     if(cell ==nil){
 68         cell = [[UITableViewCell alloc ] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier ];
 69         
 70     }
 71     NSUInteger row = [indexPath row];
 72     
 73     cell.textLabel.text = [listData objectAtIndex:row];
 74     ///给每一行添加图片
 75     UIImage *image = [UIImage imageNamed:@"blue.png"];
 76     cell.imageView.image = image;
 77     ///设置点击之后的图片
 78     UIImage *highlighedImage = [UIImage imageNamed:@"yellow.png"];
 79     cell.imageView.highlightedImage = highlighedImage;
 80     ///设置详细信息 类似小标题 cell 的默认样式不显示 可以试试其他样式
 81     cell.detailTextLabel.text = @"Detail";
 82     /// 设置字体大小
 83     cell.textLabel.font = [UIFont boldSystemFontOfSize:40];
 84     return  cell;
 85     
 86 }
 87 ///设置缩进
 88 - (NSInteger) tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath{
 89     NSInteger row = [indexPath row];
 90     return  row;
 91 }
 92 ///允许奇数列可以点击
 93 - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath  {
 94     NSInteger row = [indexPath row];
 95     if(row%2 ==0){
 96         return  nil;
 97     }
 98     return indexPath;
 99 }
100 
101 
102 ////设置点击某行弹出消息
103 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
104     NSUInteger row = [indexPath row];
105     NSString *rowValue = [listData objectAtIndex:row];
106     
107     NSString *message = [[NSString alloc] initWithFormat:@"YOU select %@",rowValue];
108     
109     UIAlertView *alert = [[UIAlertView alloc ] initWithTitle:@"Row Selected!" message:message delegate:nil cancelButtonTitle:@"Yes id did" otherButtonTitles:nil, nil];
110     [alert show];
111     
112     [tableView deselectRowAtIndexPath:indexPath animated:YES];
113 }
114 
115 - (void)viewWillAppear:(BOOL)animated
116 {
117     [super viewWillAppear:animated];
118 }
119 ///设置快捷见右侧  通讯录右侧类似
120 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView{
121     return [NSMutableArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",
122             @"G",@"H",@"I",@"J",@"K",@"L",
123             @"M",@"N",@"O",@"P",@"Q",@"R",
124             @"S",@"T",@"U",@"V",@"W",@"X",
125             @"Y",@"Z",@"#", nil];  
126 }
127 
128 - (void)viewDidAppear:(BOOL)animated
129 {
130     [super viewDidAppear:animated];
131 }
132 
133 - (void)viewWillDisappear:(BOOL)animated
134 {
135     [super viewWillDisappear:animated];
136 }
137 
138 - (void)viewDidDisappear:(BOOL)animated
139 {
140     [super viewDidDisappear:animated];
141 }
142 
143 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
144 {
145     // Return YES for supported orientations
146     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
147 }
148 
149 @end

 

转自:http://blog.csdn.net/yangxt/article/details/7422466

posted on 2012-07-19 15:02  djy_fn  阅读(1133)  评论(0编辑  收藏  举报

导航