2012-07-26 90 views
1

我试图在iPhone上为UITableView实现此功能:总是只有FIRST和LAST VISIBLE单元具有不同的背景颜色,例如红色,而其他单元格的颜色保持不变白色。并在滚动过程中进行平滑更改。
我曾尝试:uitableview第一次和最后一次可见的单元格颜色变化

.m文件:

NSIndexPath *firstRow; 
UITableViewCell* firstCell; 

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

    if (cell == nil) 
    { 
     NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"tableCell" owner:self options:nil]; 
     cell = [nib objectAtIndex:0]; 
    } 

    cell.nameLabel.text = [tableData objectAtIndex:indexPath.row]; 
    //cell.thumbnailImageView.image = image; 

    return cell; 
} 

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath; 
{ 
    NSArray *visible = [tableView indexPathsForVisibleRows]; 
    firstRow = (NSIndexPath *)[visible objectAtIndex:0]; 
    firstCell = [tableView cellForRowAtIndexPath:firstRow]; 
    firstCell.contentView.backgroundColor=[UIColor redColor]; 
    NSLog(@"main visible cell's row: %i", firstRow.row); 
    [tableView endUpdates]; 
    firstCell.contentView.backgroundColor=[UIColor redColor]; 
} 

但颜色不会更新滚动备份时。

+0

更多的代码。将代码发布到'cellForRowAtIndexPath' – samfisher 2012-07-26 17:12:44

+0

好吧。 @samfisher – 2012-07-26 17:19:20

+0

是否有你在'willDisplayCell'中调用'cellForRowAtIndexPath'的原因?数据源委托本身调用'cellForRowAtIndexPath';你不应该用其他方法来调用它。 – 2012-07-26 17:41:26

回答

5

你可以做使得代码如果你想的话,它全部在cellForRowAtIndexPath中。需要

 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSString *tableViewCellID = @"cellID";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableViewCellID]; if (!cell) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableViewCellID]; [[cell textLabel] setText:[NSString stringWithFormat:@"some sting %i", [indexPath row]]]; NSArray *visibleCells = [tableView visibleCells]; for (int i = 0; i < [visibleCells count]; i++) { UITableViewCell *cell = [visibleCells objectAtIndex:i]; if (i == 0 || i == [visibleCells count] - 1) [cell setBackgroundColor:[UIColor redColor]]; else [cell setBackgroundColor:[UIColor clearColor]]; } return cell;

}

+0

非常好,非常感谢你! – 2012-07-26 18:03:52

-1

在你

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

尝试是这样的

//Find the first row 
if(indexPath.row == 0){ 
    cell.contentView.backgroundColor = [UIColor redColor]; 
} 

,并检查了最后一排,你应该重用你

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

改变了第一个单元格卷的颜色。我的意图是让第一个和最后一个ON SCREEN单元变为红色。有点像动画。 – 2012-07-26 17:27:35

相关问题