UITableView用来以表格的形式显示数据。关于UITableView,我们应该注意:
(1)UITableView用来显示表格的可见部分,UITableViewCell用来显示表格的一行。
(2)UITableView并不负责存储表格中的数据,而是仅仅存储足够的数据使得可以画出当前可见部分。
(3)UITableView从UITableViewDelegate协议获取配置信息,从UITableViewDataSource协议获得数据信息。
(4)所有的UITableView实现时实际上只有一列,但是我们可以通过向UITableViewCell中添加子视图,使得它看起来有好几列。
(5)UITableView有两种风格:
① Grouped:每一组看起来像是圆矩形;
② Plain:这是默认风格,可以修改成Indexed风格。
UITableViewCell使用实例
在下边的小例子中,我们将先实现显示一列数据,然后在每行添加图像,之后再看看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,在其中添加代码:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource> @property (strong, nonatomic) NSArray *listData; @end
5.1 在@implementation后面添加代码:
@synthesize listData;
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSArray *array = [[NSArray alloc] initWithObjects:@"Tree", @"Flower", @"Grass", @"Fence", @"House", @"Table", @"Chair", @"Book", @"Swing" , 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 *TableSampleIdentifier = @"TableSampleIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: TableSampleIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier]; } NSUInteger row = [indexPath row]; cell.textLabel.text = [listData objectAtIndex:row]; return cell; }
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: TableSampleIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];
cell.textLabel.text = [listData objectAtIndex: row];
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;
可以看到,每行左边都出现一张图片。当选中某行,其图片改变。
8、设置行的风格:
表示UITableViewCell风格的常量有:
UITableViewCellStyleDefault UITableViewCellStyleSubtitle UITableViewCellStyleValue1 UITableViewCellStyleValue2
cell.detailTextLabel.text = @"Detail Text";
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];
UITableViewCellStyleDefault
UITableViewCellStyleSubtitle
UITableViewCellStyleValue1
UITableViewCellStyleValue2
9、设置缩进:
将所有行的风格改回UITableViewCellStyleDefault,然后在@end之前添加代码如下:
#pragma mark Table Delegate Methods - (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath { NSUInteger row = [indexPath row]; return row; }
10、操纵行选择:
在@end之前添加代码:
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSUInteger row = [indexPath row]; if (row%2 == 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 deselectRowAtIndexPath:indexPath animated:YES]; }
而且关闭提示框后,选择的那行也被取消了选择,用的语句
[tableView deselectRowAtIndexPath:indexPath animated:YES];
cell.textLabel.font = [UIFont boldSystemFontOfSize:50];
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 70; }
可任意自定义的UITableViewCell
UITableView的强大更多程度上来自于可以任意自定义UITableViewCell单元格。通常,UITableView中的Cell是动态的,在使用过程中,会创建一个Cell池,根据每个cell的高度(即tableView:heightForRowAtIndexPath:返回值),以及屏幕高度计算屏幕中可显示几个cell。而进行自定义TableViewCell无非是采用代码实现或采用IB编辑nib文件来实现两种方式,本文主要收集代码的方式实现各种cell自定义。
1.如何动态调整Cell高度
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero]; label.tag = 1; label.lineBreakMode = UILineBreakModeWordWrap; label.highlightedTextColor = [UIColor whiteColor]; label.numberOfLines = 0; label.opaque = NO; // 选中Opaque表示视图后面的任何内容都不应该绘制 label.backgroundColor = [UIColor clearColor]; [cell.contentView addSubview:label]; [label release]; } UILabel *label = (UILabel *)[cell viewWithTag:1]; NSString *text; text = [textArray objectAtIndex:indexPath.row]; CGRect cellFrame = [cell frame]; cellFrame.origin = CGPointMake(0, 0); label.text = text; CGRect rect = CGRectInset(cellFrame, 2, 2); label.frame = rect; [label sizeToFit]; if (label.frame.size.height > 46) { cellFrame.size.height = 50 + label.frame.size.height - 46; } else { cellFrame.size.height = 50; } [cell setFrame:cellFrame]; return cell; }- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath]; return cell.frame.size.height; }
方法二:
在cell里添加一个像素的imageView后将图片载入进,之后设置tableView.separatorStyle = UITableViewCellSeparatorStyleNone
3.自定义首行Cell与其上面导航栏间距
tableView.tableHeaderView = [[[UIView alloc] initWithFrame:CGRectMake(0,0,5,20)] autorelease];
UIButton *button; if(isEditableOrNot) { UIImage *image = [UIImage imageNamed:@"delete.png"]; button = [UIButton buttonWithType:UIButtonTypeCustom]; CGRect frame = CGRectMake(0.0,0.0,image.size.width,image.size.height); button.frame = frame; [button setBackgroundImage:image forState:UIControlStateNormal]; button.backgroundColor = [UIColor clearColor]; cell.accessoryView = button; }else{ button = [UIButton buttonWithType:UIButtonTypeCustom]; button.backgroundColor = [UIColor clearColor]; cell.accessoryView = button; }
[button addTarget:self action:@selector(btnClicked:event:) forControlEvents:UIControlEventTouchUpInside];
但我们还是可以利用event参数,在自定义的btnClicked方法中判断出事件发生在UITableView的哪一个cell上。因为UITableView有一个很关键的方法indexPathForRowAtPoint,可以根据触摸发生的位置,返回触摸发生在哪一个cell的indexPath。而且通过event对象,正好也可以获得每个触摸在视图中的位置。
// 检查用户点击按钮时的位置,并转发事件到对应的accessory tapped事件 - (void)btnClicked:(id)sender event:(id)event { NSSet *touches = [event allTouches]; UITouch *touch = [touches anyObject]; CGPoint currentTouchPosition = [touch locationInView:self.tableView]; NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition]; if(indexPath != nil) { [self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath]; } }
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { int *idx = indexPath.row; //这里加入自己的逻辑 }
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。