1
votes

I have a CollectionView which I use to show my feed in my social app. I am now trying to add new posts to the feed, which works fine. However, sometimes, when the added cells take up the entire screen height, the note attached to the post is not shown. This is because I have a validation which checks if the note is empty, and if it is, the subview of the note textview is removed and the constraints are changed. Take a look at the image to see what I mean (apologies for the poor quality, I was restricted to 2 MB):

Missing Note

This is where it goes wrong, in my cellForItemAt method. I have two arrays: posts and userInfo, which are filled with data correctly, because if I print all the data in cellForItemAt, it all shows as expected.

if let postNote = posts[indexPath.item].postNote {
    if(postNote.isEmpty) {
        socialCell.noteTextView.removeFromSuperview()
        socialCell.postDetailsView.bottomAnchor.constraint(equalTo: socialCell.noteTextView.bottomAnchor).isActive = false
        socialCell.postDetailsView.bottomAnchor.constraint(equalTo: socialCell.postName.bottomAnchor).isActive = true
    }
}

What I am trying to do here, is decide whether the constraints should be set to the note or to the name of the post, depending on if there is a note or not. If I comment out this code, the constraints are not as they should be (obviously), but all notes are shown. So I am certain the issue can be found here: my string of the note is seen as empty, while it is not. Printing out the array or print(postNote) returns the right value.

What is happening here and how should I fix it?

1

1 Answers

-1
votes

Cells are re-used. When a cell that previously had an empty note is reused for a post with a non-empty note you need to ensure that the constraints are set correctly or the note will still be hidden.

Also, you don't want to keep adding constraints as the cell is re-used. You should add the two constraints, once, in your custom cell class and then just set them to active/inactive as required.

Finally, don't remove the noteTextView, as again, when the cell is re-used it won't be available in the case where there is a note. You should simply set it to isHidden = true or just hide it with the constraints

Something like:

socialCell.noteTextView.isHidden = true
socialCell.hideNoteConstraint.isActive = true
socialCell.showNoteConstraint.isActive = false

if let postNote = posts[indexPath.item].postNote, !postNote.isEmpty {
    socialCell.noteTextView.isHidden = true
    socialCell.hideNoteConstraint.isActive = false
    socialCell.showNoteConstraint.isActive = true
}