UITableView, 用封装类的方法给cell赋值

#import "RootViewController.h"

#import "Person.h"

@interface RootViewController ()<UITableViewDataSource>

@property (nonatomic, retain)NSMutableArray *array;

@end

@implementation RootViewController

- (void)dealloc

{

    [_array release];

    [super dealloc];

}

- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor cyanColor];

    

    //创建导航控制器, 需要一个视图控制器, 所以要先创建一个视图控制器, 这样导航控制器就会管理这个试图控制器

    //让导航控制器成为appdelegate的根视图控制器

    

    //UITableView 的移动 和 编辑

    

    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain)];

    tableView.rowHeight = 100;//行高, 默认值是44

    tableView.backgroundColor = [UIColor yellowColor];

    tableView.dataSource = self;//指定代理, 让代理来提供数据

    

    

    [self.view addSubview:tableView];

    [tableView release];

    [self creatData];//把一部分代码转移到, 一个方法中

    

    

    

}

- (void)creatData {

    Person *p1 = [Person personWithName:@"阿呆" number:@"123"];

    Person *p2 = [Person personWithName:@"阿狸" number:@"456"];

    Person *p3 = [Person personWithName:@"蹦蹦" number:@"789"];

    Person *p4 = [Person personWithName:@"跳跳" number:@"423"];

    self.array = [NSMutableArray arrayWithObjects:p1, p2, p3, p4, nil];

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];//收到内存警告, 被动触发

    

}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {//设置行数

    return self.array.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    //创建cell

    //1.设置标识符,找cell

     static NSString *str = @"cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];//在重用池中找cell

    if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:str] autorelease];//直接release不合适, 所以用autorelease

    }

    //给cell赋值

//    cell.textLabel.text = @"name";

//    cell.detailTextLabel.text = @"phone";

    

    Person *person = [self.array objectAtIndex:indexPath.row];

    cell.textLabel.text = person.name;

    cell.detailTextLabel.text = person.number;

    

    return cell;

    

    

    

}

@end

原文地址:https://www.cnblogs.com/hsxblog/p/4921770.html