iOS开发 -创建一个简单的TableView

来源:互联网 发布:电子狗数据更新 编辑:程序博客网 时间:2024/06/16 20:59

iOS学习 -创建一个简单的TableView程序

1,创建工程

在workspace中添加一个工程“SimpleTable”,创建完成后,设定此项目为当前调试、运行工程:Product->Scheme



2,在ViewController中添加TableView

打开Main.storyboard,在右下角的控件窗口中拖动Table View到ViewController中,拖动完成后,如下图:


3,修改代码

打开ViewController.h文件,修改为如下代码:

#import <UIKit/UIKit.h>@interface SimpleTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>@end
UITableView是表视图幕后的实际类,用来处理不同类型的数据;

UITableviewDataSource用来连接数据和表视图,要求实现两个方法:tableView:cellForRowAtindexPath、tableView:numberOfRowsInSection

在ViewController.m中定义一个实例变量,存放表数据:

@implementation SimpleTableViewController//存放表数据的实例变量,存放表数据NSArray *tableData;

在viewDidLoad中初始化数据:

-(void)viewDidLoad {    [super viewDidLoad];        //初始化列表数据    tableData = [        NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast",                 @"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast",                 @"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast",                 @"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast",                 @"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast",                 nil                 ];}
numberOfRowsInSection通知表视图选择了多少行数据,也就是tableData有多少个元素:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {    return [tableData count];}

cellForRowAtIndexPath获取某一个cell的内容:

//每一次数据行显示的时候,都会调用cellForRowAtIndexPath方法-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    static NSString *simpleTableIdentifier = @"SimpleTableItem";    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];    if (cell == nil) {        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];    }    cell.textLabel.text = [tableData objectAtIndex:indexPath.row];    return cell;}
ok,至此,代码部分已完成开发。但是再次运行依旧看不到任何内容,为什么呢?因为还没有把表视图和数据源连接起来。

4,连接视图和委托

因为我们修改了ViewController.h中定义的接口名字为:SimpleTableViewController,我们第一步来修改Main.storyBoard中的View Controller对应的Custome Class,如图所示,选中黄底白框的图标,在右侧的"class"中输入“SimpleTableViewController”:


   设立数据源和代理的委托:在Table View区域右击:

   

鼠标放入到dataSource后面的圆圈中,按下左键拖动到如图所示的位置,释放鼠标即可。


同样的方法设置delegate即可,再次运行即可看到页面中显示的列表:

5,为每一行数据添加一个图标

   我平时找练习用的图标在这个网站中找:http://www.easyicon.net,随便下载一个图标,加入到工程,此处找了个鸡蛋的图标命名为egg.png,在cellForRowAtIndexPath中的return cell之前加入这行代码:

   

cell.imageView.image = [UIImage imageNamed:@"egg.png"];
再此运行即可看到每个列表项前都有一个鸡蛋的图标了。


6,总结

  1,修改了ViewController.h中的interface后,没有修改main.storyBoard中的Custom Class的属性,导致连接数据源、代理后依旧不能显示设定的数据;

  2,没看过OC的语法,抄代码时很费劲,接下来找本OC的电子书看看。


代码地址: https://git.oschina.net/woodlouse/IosLearing.git


0 0
原创粉丝点击