2012-11-22 50 views
1

我用的cellForRowAtIndexPath喜欢这里:如何仅将UITableView的第一个单元格设置为不同的颜色?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if(cell == nil) 
     cell = [self getCellContentView:CellIdentifier]; 


    UILabel *lbl = (UILabel*)[cell.contentView viewWithTag:1]; 

    for (UITableViewCell *c in [tbl visibleCells]) 
    { 
    // UITableViewCell *cell2 = [tbl cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]]; 
     UILabel *lbl = (UILabel*)[c.contentView viewWithTag:1]; 
     lbl.textColor = [UIColor redColor]; 
    } 

    if([tbl indexPathForCell:cell].section==0) 
     lbl.textColor = [UIColor whiteColor]; 


    UILabel *lblTemp1 = (UILabel *)[cell viewWithTag:1]; 
    UILabel *lblTemp2 = (UILabel *)[cell viewWithTag:2]; 

    //First get the dictionary object 

    lblTemp1.text = @"test!"; 
    lblTemp2.text = @"testing more"; 

    NSLog(@"%@",[tbl indexPathForCell:cell]); 

    return cell; 


} 

,但仍让我的一些细胞白色的而不是灰色的。

如何才能将行中的第一个项目更改为白色?

回答

5

第一:沟

for (UITableViewCell *c in [tbl visibleCells]) 
{ 
    //UITableViewCell *cell2 = [tbl cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]]; 
    UILabel *lbl = (UILabel*)[c.contentView viewWithTag:1]; 
    lbl.textColor = [UIColor redColor]; 
} 

,并更改为

UILabel *lbl = (UILabel*)[c.contentView viewWithTag:1]; 
lbl.textColor = [UIColor redColor]; 

没有必要去这里低谷所有可见的单元格。

然后改变

if([tbl indexPathForCell:cell].section==0) 
     lbl.textColor = [UIColor whiteColor]; 

if((indexPath.section==0)&&(indexPath.row==0)) 
     lbl.textColor = [UIColor whiteColor]; 

如果这个类/对象几个tableViews的代表,你应该 添加额外的检查为

if ((tableView == correctTableView)&&... 

值得注意到,

[tbl indexPathForCell:cell] 

是irelevant。您的参考是参数(NSIndexPath *)indexPath

如果问题仍然存在,您应该发布您的getCellContentView:方法的代码。

编辑:根据rmaddy的建议,因为cellForRowAtIndexPath:是重要的性能,虎钳这将是更好地使用:你避免不必要的双重变化

if((indexPath.section==0)&&(indexPath.row==0)) 
{ 
    lbl.textColor = [UIColor whiteColor]; 
} 
else 
{ 
    lbl.textColor = [UIColor redColor]; 
} 

这样,其中第一小区的时候。

+1

有条件地改变单元状态的'if'语句必须有'else'语句来重置更改。否则奇怪的事情将发生,因为单元格在滚动期间被重新使用。 – rmaddy

+0

在条件变为白色之前会出现无条件变为红色 - 所以它将正常工作。但是你是对的:更好的方法是使用if/else –

+0

@rmaddy:我重新排列了代码的部分,以便它们(应该)更有意义 –

相关问题