自定义tableview的内容

来源:互联网 发布:微商卖软件赚钱吗 编辑:程序博客网 时间:2024/05/01 21:54

根据需要,我需要使用tableview的结构,但是里面每一个cell,又需要自己的样式,所以学习了一下怎样把自己定义的cell加到tableview里面,类似于新浪微博的那样。

1 。 用代码实现的方法不是很难。首先我们需要定义自己样式的cell,这个cell定义成什么样子,怎么定义是大家的事情,做过一些界面的朋友应该都很有心得的,只有一个最基本的东西需要注意,就是,一定要继承UITableViewCell这个类,要不然tableview里面无法识别,我原来继承的是scrollview,会直接崩溃。

2. 在tableview里面,要把我们自己定义的cell复制给系统的cell.(例子)

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

{

    

    static NSString *CellIdentifier = @"loadCell";

    

    UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIdentifier];

    }

    

    // 这里我把自己定义的元素项复给系统的cell了

    cell = cellForMySelf; 

    // 设置cell 的背景颜色

    cell.contentView.backgroundColor = [UIColor grayColor];

     

    return cell;

}

这样基本上就完成了基本的抄作。


3. 由于我的每一个cell的高度要求是不相同的,类似于微博。每个 cell要有不同的高度。

其实想要改变UITableView的Cell高度并不难,UITableView带有一个rowHeight属性,使用他就可以改变高度了。但是这样的改变是把所有的Cell的高度都统一改变了。如果存在不同的内容就有不同的Cell高度,那么这时候rowHeight显得力不从心了。不过iOS似乎考虑到了这一点,在UITableView的UITableViewDelegate委托下有一个委托方法可以动态地指定Cell的高度,其声明如下:

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

还有一点要注意的是在heightForRowAtIndexPath是不能使用UITableView的cellForRowAtIndexPath:返回Cell对象的。否则会导致无限级递归调用引发的堆栈溢出 。

因为heightForRowAtIndexPath 是先于cellForRowAtIndexPath被系统调用,这个时候cell并没有生成。


顺便唠叨下tableView的用法:

一般顺利的完成tableView需要实现以下几个方法:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

     

    // Return the number of sections.这里的sections意思是几个组,一般都是一个组,如果有多个组,还需要实现以下这个方法

    return 1

}


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

{

   // #warning Incomplete method implementation.

    // Return the number of rows in the section.如左,每一组里面包含几个cell的元素

    return  [moviesArray count];

   

}

//每一组的名字

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {       

 NSString *title = nil;

    switch (section) {

         case 0:   //            title = @"section 0, 标题"; 

            break;

        case 1:

            title = @"section 1";

            break;

        default:

            break;

    }

    

    return title;

}



原创粉丝点击