ios学习笔记 UITableView(纯代码) (二)

头文件

---------------------------------------------

#import <UIKit/UIKit.h>

 

/**

 UITableViewDataSource 表视图数据源协议,用来控制表视图的显示内容

 UITableViewDelegate 表视图协议 用来控制表视图的显示以及每一个cell的高度和每个分区的头尾高度等

 

 协议的介绍   https://www.cnblogs.com/jukaiit/p/4702797.html

 */

@interface ViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>

{

    UITableView * tableView;

    NSArray * array;

}

//引用UITableView

@property (strong,nonatomic)UITableView * tableView;

 

//存放数据的数组

@property (strong,nonatomic) NSArray * array;

 

@end

 

--------------------------------------------------------

 

 

#import "ViewController.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController

 

 

//功能:让编译器自动编写一个与数据成员同名的方法声明来省去读写方法的声明。

// 详情 https://www.cnblogs.com/AnnieBabygn/p/7742628.html

@synthesize tableView;

@synthesize array;

 

- (void)viewDidLoad {

    [super viewDidLoad];

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

    

    [self MyArray];

    [self MyTableView];

}

 

//定义的tableView

-(void) MyTableView

{

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

    

    tableView.dataSource = self;

    tableView.delegate = self;

    [self.view addSubview:tableView];

}

 

//添加数据

-(void) MyArray

{

    

    NSMutableArray * MutableArr = [[NSMutableArray alloc] init];

    for (int i = 0; i < 15 ; i++) {

        NSString * value = [NSString stringWithFormat:@"this is  %d cell",i];

        [MutableArr addObject:value];

    }

    array = MutableArr;

}

 

// 这个函数是显示tableview的 section 个数

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 1;

}

 

// 显示多少个 cell

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

{

    //取决于数组的长度

    return [array count];

}

 

// cell 的内容

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

{

    //防止重复的TableView

    static NSString * CellIdentifier = @"MyCell";

    

    //减少内存  和上一篇的有一点点不一样

    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell == nil)

    {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];

    }

    //遍历数组

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

    

    return cell;

}

 

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

 

@end

猜你喜欢

转载自www.cnblogs.com/wangbaishi/p/9230089.html