Table View 在iOS开发中是一个很重要的控件。数据库
从Object Library中能够找到Table View控件。segmentfault
在创建的项目文件目录选择Main.Storyboard
切换到Storyborad界面,而后从Object Library从拖拽Table View控件到View中。ide
将文件SimpleTableViewController.h
修改代码以下:spa
@interface SimpleTableViewController:UIViewController <UITableViewDelegate, UITableViewDataSource>
PS.我这里项目Class prefix是SimpleTable。
而后在SimpleTableViewController.m
中定义一个instance variable 用来存储将要在Table View 中显示的数据。code
@implementation SimpleTableViewController{ NSArray *dataList; }
而且在viewDidLoad
方法中初始化和赋值。图片
-(void)viewDidLoad { [super viewDidLoad]; dataList = [NSArray arrayWithObjects:@"item1",@"item2",@"item3",nil]; }
如今咱们添加两个方法:tableView:numberOfRowsInSection
和tableView:cellForRowAtIndexPath
。这两个方法是UITableViewDataSource
协议中的一部分。ip
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [dataList count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *identifier = @"SimpleTableIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; if(cell == nil){ cell = [UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]; } cell.textLabel.text = [dataList objectAtIndex:indexPath.row]; return cell; }
如今还须要在Table View
和DataSource
与Delegate
之间创建connection。
切换到Storyboard
界面中选择Table View并右键,获得以下:ci
能够看到Outlets中有dataSource和delegate两个项目,如今须要将这两个项目和Simple Table View Controller
之间创建connection。方法是按住dataSource和delegate右侧的圆圈而后拖拽到Simple Table View Controller
上,以下图所示:开发
最终获得以下:it
而后运行
添加缩略图
「Add Files to "SimpleTable"...」
而后添加一张图片。我这里添加的是wallpaper-1791868.jpg
而后在方法tableView:cellForRowAtIndexPath:
中添加如下代码:
cell.imageView.image = [UIImage imageNamed:@"wallpaper-1791868.jpg"];
而后运行查看效果。
上面直接将数据直接保存在代码中,在实际开发中好的实践应该是代码和数据分离,将数据保持到数据库或者本地文件中。因此这里要提到Property list文件。
新建一个Property list文件
编辑Property list文件
而后咱们来读取Property list文件中的数据
NSString *path = [NSBundle mainBundle] pathForResource:@"recipes" ofType:@"plist"]; NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path]; tableData = [dict objectForKey:@"Recipes Name"]; thumbnail = [dict objectForKey:@"Thumbnail"]; prepTime = [dict objectForKey:@"prepTime"];
修改tableView:numberOfRowsInSection:
和tableView:cellForRowAtIndexPath:
方法的代码。
- (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [tableData count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *simpleTableIdentifier = @"SimpleTableIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; if(cell == nil){ cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier]; } cell.textLabel.text = [tableData objectAtIndex:indexPath.row]; cell.imageView.image = [UIImage imageNamed:[thumbnail objectAtIndex:indexPath.row]]; return cell; }
运行,能够发现读取数据成功。