【ios6.0 自学瞎折腾】(三)表示图填充数据

1.首先拖入TableView;

2.然后再ViewController接口文件中添加UITableViewDelegate,UITableViewDataSource委托协议;

//
//  BvinViewController.h
//  TestTableView
//
//  Created by Bvin on 12-12-27.
//  Copyright (c) 2012年 Bvin. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface BvinViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>

@end

3.然后再ViewController的实现文件中,声明一个字符串数组属性,用以填充tableView(其实就相当于android里的listview),并在viewDidLoad;方法里实力化赋值。

{
    NSArray *tableData;

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    tableData = [NSArray arrayWithObjects:@"[1]南昌-Bvin",@"[1]南昌-宝宝",@"[12]B5+",@"[12]bugFix",@"[123]西班牙斗士",@"[23]福建-冰凝",@"[1]小破孩",@"[13]蜗牛哥",@"[1]大卫",@"[1]广州-风",@"[1]北京-甜瓜", nil];
    //初始化赋值
}

4.实现委托的两个必要方法tableView:numberOfRowsInSection:和tableView:cellForRowAtIndexPath:,前一个是返回item的总量,后面就是获取一个viewHold(用android的话来说),返回一个UITableViewCell对象,其实这个对象就相当于android中的adapter,然后用cell.textLable.text去获取数组里每个元素。

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


-(UITableViewCell*) tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"TestTableViewItem";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    //返回可重用的cell
    if(cell==nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
            reuseIdentifier:identifier];
        //如果没有可重用的,就新建一个
    }
    cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
    //把数据源填充进去
    return cell;
}

这就像android中adapter的getItemCount()方法和getView()方法。为了高效率android采用的viewHolder方法,其实就是仿照cell的方法,回收重用。

5.然后把TableView与协议和委托链接起来,同样再xib中把TableView拖向File's Owner进行链接,连接好了就可以run一遍了!!!

后语:

  由于是从android转过来的,对oc很多不懂,其实再弄这个小demo期间还是除了几个小失误!!

  要谨慎,还有oc基础得去充电。

原文地址:https://www.cnblogs.com/bvin/p/2836606.html