Faisal Syed Faisal Syed - 23 days ago 7
Swift Question

How to keep subview on UITableViewCell

When the user taps the accessory view, the profile image in the UITableViewCell gets darkened by a black view that gets added on as a subview.

Here is what the cell looks like with the black subview:

enter image description here

Here's the issue: When I tap on another cell, the subview gets removed from the first cell and added to the second:

enter image description here

I would like to keep the subview for all cells that have been tapped.

Here is the code in which I handle that functionality:

self!.profileImageBlackView.cornerRadius = cell.followUserImage.frame.height/2
self!.profileImageBlackView.frame = cell.followUserImage.frame
cell.followUserImage.addSubview(self!.profileImageBlackView)
cell.followButton.hidden = false


For some reason, the follow button gets added to both cells, but the "profileImageBlackView" gets moved from cell to cell depending upon which one was activated.

Answer

You cannot display the same view in different cells. If you add the view to another cell it's removed from the first one. You must create a separate view for each cell.