简单表视图并实现添加数据

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.编写控制器

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

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

#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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值