UITableView设置背景颜色 [英] UITableView set background color

查看:183
本文介绍了UITableView设置背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 tableView:cellForRowAtIndexPath 方法中更改UITableViewCells的背景颜色

I change the background color of the UITableViewCells in the tableView:cellForRowAtIndexPath method

    if(indexPath.row % 2 == 0){
        cell.backgroundColor = ...
    } else{
        cell.backgroundColor = ...
    }

但这只会改变 tableView:numberOfRowsInSection 中指定的单元格数量的颜色(如附图,前四个后有白色单元格)

But that only change the color of the cell amount specified in tableView:numberOfRowsInSection (As seen in the attached picture, there are white cells after the first four)

是否可以更改屏幕上显示的所有单元格的颜色?

Is it possible to change the color of all cells that are displayed on screen?

推荐答案

如果希望单元格背景颜色继续交替,那么您需要说明表格中有多少行。具体来说,在 tableView:numberOfRowsInSection 中,您需要始终返回一个将填充屏幕的数字,并在 tableView:cellForRowAtIndexPath 中,为超出结尾的行返回一个空白单元格的表。以下代码演示了如何执行此操作,假设 self.dataArray 是NSStrings的NSArray。

If you want the cell background color to continue to alternate, then you need to lie about how many rows are in the table. Specifically, in tableView:numberOfRowsInSection you need to always return a number that will fill the screen, and in tableView:cellForRowAtIndexPath, return a blank cell for rows that are beyond the end of the table. The following code demonstrates how to do this, assuming that self.dataArray is an NSArray of NSStrings.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ( self.dataArray.count < 10 )
        return( 10 );
    else
        return( self.dataArray.count );
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SimpleCell"];

    if ( indexPath.row % 2 == 0 )
        cell.backgroundColor = [UIColor orangeColor];
    else
        cell.backgroundColor = [UIColor redColor];

    if ( indexPath.row < self.dataArray.count )
        cell.textLabel.text = self.dataArray[indexPath.row];
    else
        cell.textLabel.text = nil;

    return cell;
}

这篇关于UITableView设置背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆