View is getting replaced while Scrolling in UITableView

后端 未结 1 1124
自闭症患者
自闭症患者 2021-01-29 09:08

I am an Android Developer and very new to iOS App Development. I am trying to build a simple chat system with only one line of data in each cell.

I am using a custom

1条回答
  •  盖世英雄少女心
    2021-01-29 09:47

    You need to move your code that adds the subviews to the cell from the cellForRowAt delegate to inside their respective cell classes.

    The problem right now like @PeteMorris said, is that your cells which will be reused will already have the subviews which you added when it was dequeued the first time. So whenever the same cell is dequeued, subviews are added to it again.

    • The elegant solution would be to move the code that sets up the view to inside your cell class.

    • If you are looking for a hotfix you could remove all the subviews from the cell in prepareForReuse. (This method is called every time your cell is reused before dequeue-ing)

    Your reuse method would look like this. (This method is inside your cell class)

    override func prepareForReuse() {
        super.prepareForReuse()
    
        for view in subviews {
            view.removeFromSuperview()
        }
    }
    

    0 讨论(0)
提交回复
热议问题