Reputation: 5754
I want to show last visible cell with different background color (say green). I am using this code, It works good until I scroll up/down. When I scroll up/down it gives many cell with green background. (I guess this happening due to "dequeueReusableCellWithIdentifier"). Can anyone help me out where I am doing wrong or what is the best way of doing this.
NSArray* indexPaths = [tableView indexPathsForVisibleRows];
if (indexPath.row==[indexPaths count]-1)
{
UIView *v=[[UIView alloc]initWithFrame:cell.bounds];
v.backgroundColor=[UIColor greenColor];
cell.backgroundView=v;
}
Thanks in advance.
Upvotes: 1
Views: 236
Reputation: 9
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row==[yourtableviewarray count]-1)
{
UIView *v=[[UIView alloc]initWithFrame:cell.bounds];
v.backgroundColor=[UIColor greenColor];
cell.backgroundView=v;
}
}
Upvotes: 0
Reputation: 1429
Firstly, you shouldn't be allocating anything in cellForRowAtIndexPath
- it is bad for performance. You should only be configuring views and controls that already exist for every cell. Because cells are reused, your cell that you add a background view to will get re-used too... and its background view.
In your case, you probably just want to set:
if (lastCell)
cell.contentView.backgroundColor = [UIColor greenColor];
else
cell.contentView.backgroundColor = [UIColor clearColor]; //or whatever color
contentView
is already a view every UITableViewCell
has for free, so just use that for background color. Apple probably intended it to be used for this case, amongst others.
Upvotes: 2
Reputation: 1964
You should nil the background view before the test.
cell.backgroundView = nil;
if (indexPath.row==[indexPaths count]-1)
{
UIView *v=[[UIView alloc]initWithFrame:cell.bounds];
v.backgroundColor=[UIColor greenColor];
cell.backgroundView=v;
}
Upvotes: 0