My data displays correctly before any scrolling happens on the UITableView. Once I scroll I see data overlapping and from my understanding it is because cells get reused! I now understand the concept but not really understanding what my solution needs to be or how/where to implement one (sorry i am very new to swift). I found this Why do my UITableView cells overlap on scroll? but again don’t really know how to apply it to my code.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.lineBreakMode = .byWordWrapping
let userNameLabel = UILabel()
userNameLabel.text = activeUsers[indexPath.row].userFirstName
userNameLabel.font = userNameLabel.font.withSize(10)
userNameLabel.sizeToFit()
let userProfilePic = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
userProfilePic.image = activeUsers[indexPath.row].profilePicImage
userProfilePic.layer.borderWidth = 1.0
userProfilePic.layer.masksToBounds = false
userProfilePic.layer.borderColor = WhistleColors.primaryBorderColor.cgColor
userProfilePic.layer.cornerRadius = userProfilePic.frame.size.height / 2
userProfilePic.clipsToBounds = true
userProfilePic.contentMode = .scaleAspectFill
let userStackView = UIStackView(arrangedSubviews: [userProfilePic, userNameLabel])
userStackView.alignment = .center
userStackView.distribution = .fillEqually
userStackView.axis = .vertical
cell.addSubview(userStackView)
userStackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(
[
userStackView.centerXAnchor.constraint(equalTo: cell.contentView.centerXAnchor, constant: cell.frame.size.width / 2),
userStackView.centerYAnchor.constraint(equalTo: cell.contentView.centerYAnchor, constant: cell.frame.size.height / 2),
]
)
userProfilePic.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(
[
userProfilePic.widthAnchor.constraint(equalToConstant: 40),
userProfilePic.heightAnchor.constraint(equalToConstant: 40)
]
)
return cell
}
3
Answers
I was able to fix my issue by watching this https://www.youtube.com/watch?v=Pu7B7uEzP18 and implementing a custom cell class with a prepareForReuse() method.
The first youtube video I ever watched around UITableViews and loading data never went over the concept of "reusable cells". Wondering how many issues like this I will encounter in the future because a concept was not discussed in my learning process! Oh well. Onward. Thanks all
dont use cellForRowAt for creating ui properties.
First of all I suggest you pLease use custom cell for UI creation.
Otherwise its overlap.
Concept of tableview is to reuse cells and it’s subviews. You are creating subviews on each cell every time when it reloads. Check https://sahilpathania1997.medium.com/how-to-start-with-tableview-in-swift-bf273a8bbabe