Reputation: 809
When trying to set borders around my UITableViewCells, I have an issue where whenever the TableView is scrolled down, a border is added where I don't want it to be! I need to individually set these borders for the first and last cells because the TableView itself has a header that I don't want to include in the border. I already have a Footer so I cannot use that option either.
Here's what my code looks like:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.viewMain.addBorders(edges: [.left, .right], color: UIColor.black)
if indexPath.row == 0 {
cell.viewMain.addBorders(edges: [.top], color: UIColor.black)
} else if indexPath.row == ((self.dataArray.count ?? 1) - 1){
cell.viewMain.addBorders(edges: [.bottom], color: UIColor.black)
}
And here's what the TableView looks like when I scroll down and back up:
I had to redact the data for confidentiality, but see the issue? The borders should only be on the top and bottom, and when the view is loaded originally, it looks right. Only when the user scrolls down or the screen isn't big enough to see the whole TableView do I have this issue.
Upvotes: 1
Views: 508
Reputation: 14397
In your CustomCell
override method prepareForReuse
because this problem arises when tableView
reuse cells
class CustomCell:UITableViewCell {
override func prepareForReuse() {
//remove all borders here
}
}
Upvotes: 1
Reputation: 2922
It because the cell is recycled, you need to remove all border before adding border
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
// remove all borders here
cell.viewMain.addBorders(edges: [.left, .right], color: UIColor.black)
if indexPath.row == 0 {
cell.viewMain.addBorders(edges: [.top], color: UIColor.black)
} else if indexPath.row == ((self.dataArray.count ?? 1) - 1){
cell.viewMain.addBorders(edges: [.bottom], color: UIColor.black)
}
Upvotes: 1