2012-07-26 89 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

相關問題