---
title: "简单表视图并实现添加数据"
author: "xiaotongeye"
date: "2014-09-10T19:21:01Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-09-10T19:21:01Z"
id: 2115002
url: "https://xiaotongeye.iteye.com/blog/2115002"
---

1.基础：表用于显示数据列表。数据列表中的每项都由行表示。表视图是显示表数据的视图对象，它是UITableView类的一个实例，表中的每个可见行（表视图单元）都由UITableViewCell类实现。
2.实现表视图。
首先说明一下数据源（datasource）和委托（delegate）
在头文件中需要添加以下代码：<UITableViewDelegate,UITableViewDataSource>，它的作用是让类遵从两个协议，类需要使用这两个协议来充当表视图的委托和数据源，然后声明一个数组用于放置将要显示的数据。UITableView需要一个数据源(dataSource)来显示数据，UITableView会向数据源查询一共有多少行数据以及每一行显示什么数据等。没有设置数据源的UITableView只是个空壳。凡是遵守UITableViewDataSource协议的OC对象，都可以是UITableView的数据源。通常都要为UITableView设置代理对象(delegate)，以便在UITableView触发一下事件时做出相应的处理。
3.声明数组分为不变数组（NSArray）和可变数组（NSMutable Array）

```定义不变数组

NSArray *array = [[nsarray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil];

```


```定义可变数组

NSMutableArray *array = [[nsmutablearray alloc] init];

```

需要说明的是，创建一个NSMutableArray可以声明成NSArray，以此通知其他代码不应该修改此数组。
4.编写控制器

```ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
<UITableViewDelegate, UITableViewDataSource>
{
    UITableView *mTableView;
    NSArray *listData; 
}
@property (nonatomic, retain) NSArray *listData;
@end

```

tableView: numberOfRowsInSection:查看指定分区有多少行。
tableView: cellForRowAtIndexPath: 提供表视图单元格所需要的数据。

```ViewController.m

#import "ViewController.h"
@interface ViewController ()

@end
@implementation ViewController
@synthesize listData;
- (void)viewDidLoad
{
    [super viewdidload];
    mTableView = [[uitableview alloc]initWithFrame:CGRectMake(0, 0, [[uiscreen mainscreen] bounds].size.width, [[uiscreen mainscreen] bounds].size.height) style:UITableViewStylePlain];
    [self.view addsubview:mtableview];//实现tableview
    mTableView.delegate = self;
    mTableView.dataSource = self;
    NSArray *array = [[nsarray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil];//创建不变数组
    self.listData = array;
}
- (void)viewDidUnload{
    self.listData = nil;
    [super viewdidunload];
}

- (void)didReceiveMemoryWarning
{
    [super didreceivememorywarning];
}

#pragma mark - 
//实现TableView数据源方法
#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 *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableview dequeuereusableheaderfooterviewwithidentifier:cellidentifier];
    if (cell == nil){
        cell = [[uitableviewcell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    NSUInteger row = [indexpath row];
    cell.textLabel.text = [listdata objectatindex:row];
    return cell;
}
@end

```