Dhanesh KM
Dhanesh KM

Reputation: 449

Change border color of a UITableViewCell on selection

I am using a custom table view cell for my tableview. For setting the border, I have put a view on the custom cell and I am changing its border properties.

self.borderView.layer.borderColor = VIEW_BORDER_COLOR;

I want to highlight the selected cell by changing it's border color. I tried to change it in didselectrowforindexpath,

cell.borderView.layer.borderColor = [UIColor yellowColor].CGColor;

but as the cells are reused it changes on scrolling.

Upvotes: 17

Views: 41047

Answers (3)

user2398911
user2398911

Reputation: 94

You can use Objective-C

[cell.contentView.layer setBorderColor:[UIColor blackColor].CGColor]; 
[cell.contentView.layer setBorderWidth:2.0f]; 

Swift 5

cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 2.0

Hope it helps you.

Upvotes: 21

Victor Sigler
Victor Sigler

Reputation: 23451

Using:

Swift 2 :

cell.layer.borderWidth = 2.0
cell.layer.borderColor = UIColor.grayColor().CGColor

Swift 3

cell.layer.borderWidth = 2.0
cell.layer.borderColor = UIColor.gray.cgColor

Upvotes: 36

Ishank
Ishank

Reputation: 2926

Will have to mark/un-mark(assuming u need only one selected at a time) the border color again and again like-

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row==self.selectedRow){
cell.borderView.layer.borderColor = [UIColor yellowColor].CGColor;
}else {
cell.borderView.layer.borderColor = [UIColor clearColor].CGColor;
}
}

Just save/cache the selected index like-

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

//Unselected the prevoius selected Cell
            YourCellClass *aPreviousSelectedCell=  (YourCellClass*)[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.selectedRow inSection:0]];
            aPreviousSelectedCell.borderView.layer.borderColor = [UIColor clearColor].CGColor;

//Selected the new one-    
           YourCellClass *aSelectedCell = (YourCellClass*)[tableView cellForRowAtIndexPath:indexPath];

    aSelectedCell.borderView.layer.borderColor = [UIColor yellowColor].CGColor; 

            self.selectedRow = indexPath.row;
        }

Upvotes: 6

Related Questions