TableView的快捷使用(5分钟demo)深入前往Json和Xml解析

开门见山,动手(5分钟而已即可入门)

1、新建项目

新建一个Single View Application,命名为TableViewDemo。

TableView放上控件打开单击打开Main.storyboard,  (咱们就用生成项目时自带的视图控制器)在控件栏中找到UITableView控件,拖拽到试图控制器上(您可以全部覆盖,也可以覆盖一部分区域)

2、设置tableview的dataSource和delegate(右键)点击不放上图最上面的第一个黄色标志;然后拉到如下图最上边的最后一个按钮,连接新添加的TableView和ViewController。对于一个视图,他如何知道自己的界面的操作应该由谁来响应这个桥梁就是File's Owner。

dataSource和delegate两个选中。

3、打开ViewController.h,添加协议和Property (类似与java里的实现接口)

 #import <UIKit/UIKit.h>

 @interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>

@end

4.打开ViewController.m文件,并实现tableview的代理方法

       (1)定义全局变量list,用于装我们要显示在列表上的内容文字

       (2)在ViewDidLoad()中,对数组变量进行初始化;

(3)实现代理方法

#import "ViewController.h"

 

@interface ViewController ()

@property (nonatomic, strong) NSArray *list;

@end

 

@implementation ViewController

@synthesize list;

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    arrayData = [NSArray arrayWithObjects:@"虎",@"牛",@"宋",@"老三",@"大将军", nil];

}

#pragma mark -- delegate方法

// 1. 可选实现 如果不实现 默认是1组,返回有几组

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 1;

}

// 2. 必须实现 返回某一组有几行,根据组号返回行数

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return self.list.count;// 根据数组的数据返回行数

}

// 3. 根据下标indexPath 返回一个UITableViewCell

- (UITableViewCell *)tableView:(UITableView *)tableView

         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *TableSampleIdentifier = @"TableSampleIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:

                             TableSampleIdentifier];

    // 根据index拿到该显示的对象

//    if (!cell) //判断方法1

    if (cell == nil) {  //判断方法2

        cell = [[UITableViewCell alloc]

                initWithStyle: UITableViewCellStyleSubtitle

                reuseIdentifier:TableSampleIdentifier];

    }

//  NSUInteger row = [indexPath row];

//  cell.textLabel.text = [self.list objectAtIndex:row];

//  综合写法

    cell.textLabel.text = [self.list objectAtIndex:indexPath.row];

       return cell;

}

// 4.每组的头部显示的文字

- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

    return 0;

}

// 5.每组的最后显示的文字

- (nullable NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{

    return 0;

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

蓝色的部分敲出即可运行!!! 

posted on 2016-09-22 16:14  高彰  阅读(539)  评论(0编辑  收藏  举报

导航