下面是我们即将要实现的效果。表视图的单元格是自定义的,单击其中的项目,弹出警告框。
1.在Interface Builder,将UITableView添加到ViewController,绑定delegate和datasource到ViewController。
2.在Interface Builder,将UITableViewCell添加到UITableView,再往UITableViewCell添加自定义控件,包括一个UIImageView和UILabel。
小提醒:在命名Label和Image时,不要将Label命名为textLabel,或者将Image命名为imageView,因为textLabel和imageView属于UITableViewCell定义的变量,而我们现在要实现的是自定义单元格,要避免因为命名冲突而出现混乱。
3.新建一个类MyTableViewCell,继承UITableViewCell。同时打开storyboard和MyTableViewCell.h,按住Control键,将上图的Label拖动到MyTableViewCell.h,按照下图,将其命名为label。同理操作Image,将其命名为image。完成后MyTableViewCell.h生成如下的代码。
#import <UIKit/UIKit.h> @interface MyTableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UIImageView *image; @property (weak, nonatomic) IBOutlet UILabel *label; @end
4.在Interface Builder中选中UITableViewCell,将class设置为MyTableViewCell。将identifier设置成myTableCell(在第6步的设置单元格方法中用到)。
5.添加对UITableView的数据源初始化。图片和user_head.plist文件请见附件。
- (void)viewDidLoad { [super viewDidLoad]; [self initTableViewData]; // Do any additional setup after loading the view. } -(void)initTableViewData{ NSBundle *bundle = [NSBundle mainBundle]; NSString *plistPath = [bundle pathForResource:@"user_head" ofType:@"plist"]; dataArr = [[NSArray alloc] initWithContentsOfFile:plistPath];//dataArr为头文件定义的变量 NSLog(@"table data count = %d",[dataArr count]); }
6.将数据源绑定到UITableView。
//列表的单元数目 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [dataArr count]; } //设置单元格 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"myTableCell"; MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];//设置identifier为"myTableCell" NSUInteger row = [indexPath row]; NSDictionary *rowDict = [dataArr objectAtIndex:row]; cell.label.text = [rowDict objectForKey:@"itemName"]; NSString *imagePath = [rowDict objectForKey:@"itemImagePath"]; cell.image.image = [UIImage imageNamed:imagePath]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; return cell; }
7.相应单击事件。
//选中Cell响应事件 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ [tableView deselectRowAtIndexPath:indexPath animated:YES];//选中后的反显颜色即刻消失 NSUInteger row = [indexPath row]; NSDictionary *rowDict = [dataArr objectAtIndex:row]; NSString *userName = [rowDict objectForKey:@"itemName"]; [self showDialog:@"userName" message:userName]; } - (void)showDialog:(NSString *)title message:(NSString *)message{ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; }