<三>UITableView使用

来源:互联网 发布:linux wait源码分析 编辑:程序博客网 时间:2024/06/05 13:23

一 、设置UITableView的dataSource、delegate


•UITableView需要 通过 数据源(dataSource)来显示数据
UITableView会向数据源查询相关数据

 如: 行数、cell显示的内容等.

•不设置数据源的UITableView 不会显示数据

•只要遵守UITableViewDataSource协议的OC对象,就能成为UITableView的数据源


二 、UITableView使用


1 > •UITableView的每一行都是一个UITableViewCell,通过dataSource的tableView:cellForRowAtIndexPath:方法来初始化每一行

1. 先遵守数据源方法协议 

@property (nonatomic,assign)id <UITableViewDataSource> dataSource;


2. 设置数据源

self.tableView.dataSource = self;

或者 在StoryBoard 连线到控制器


3. 实现数据源 3个方法

//一共有多少组数据

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;

//每一组有多少行数据

-(NSInteger)tableView:(UITableView *)tableViewnumberOfRowsInSection:(NSInteger)section;

// 每一行显示什么内容

-(UITableViewCell *)tableView:(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath;


2> 用UITableView方法 

1. 要遵守 UITableViewDelegate

2. 设置代理

   self.tableView.delegate =self;

或者 在StoryBoard 连线到控制器

3. 实现代理方法
如:

/**

 *  每一行的高度不一致的时候使用这个方法来设置行高

 */

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

   if (indexPath.row ==0)return 100;

   return60;

}



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

<三> UITableView 常见属性


// 分割线

    self.tableView.separatorColor = [UIColorcolorWithRed:255/255.0green:255/255.0blue:0alpha:255/255.0];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    

    

    //表格的头部控件(直接显示表格的最顶部)

    self.tableView.tableHeaderView = [UIButtonbuttonWithType:UIButtonTypeContactAdd];

    self.tableView.tableFooterView = [[UISwitchalloc] init];



<四> Cell 常见属性

    // 取出模型

   Person *pserson = self.persons[indexPath.row];

    

    // 设置cell的数据

// 文字

    cell.textLabel.text = person.name;

   // 明细文字

    cell.detailTextLabel.text = person.intro;

   // 左边图标

    cell.imageView.image = [UIImageimageNamed:person.icon];




    // 设置cell右边指示器的类型

        cell.accessoryType =UITableViewCellAccessoryDisclosureIndicator;

//    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;

//    cell.accessoryView = [[UISwitch alloc] init];

    

    // 设置背景(背景view不用设置尺寸, backgroundView的优先级 > backgroundColor)

   UIImageView *bgView = [[UIImageViewalloc] init];

    bgView.image = [UIImageimageNamed:@"buttondelete"];

//    bgView.backgroundColor = [UIColor redColor];

    cell.backgroundView = bgView;

    

   UIView *selectedbgView = [[UIViewalloc] init];

    selectedbgView.backgroundColor = [UIColorgreenColor];

    cell.selectedBackgroundView = selectedbgView;




0 0