I'm pretty sure that what I'm seeing is some sort of issue with the dequeuing and reusing of cells, but that really doesn't make sense in context because it's only sometimes, only on some phones, and only seems to specifically affect the background color of a view.
I've got a regular old tableview that is displaying a custom class of tableviewcell I've created a xib for in the editor (basically just some labels, buttons, and colored subviews, but it's easier laying out the constraints visually in the editor than in code). Register the nib, use the dequeueReusableCellWithIdentifier
in cellForRowAtIndexPath
, everything seems to be working just fine, completely as expected. I've done this before plenty of times.
That is, up until I run it on an old iPhone 5s I've got laying around (running iOS 13, but my app is targeting 12 just to be on the safe side)- now, most but not all of the time, the background color for one of the cell's subviews isn't changing based on the code in cellForRowAtIndexPath- it's instead showing the color I've got in the nib. But everything else in cellForRowAtIndexPath runs just fine- the text for the labels gets changed, and my print()
s even show the correct If branches are being executed to change the background color.
I was tempted to believe that there was something specific about changing colors that was hanging up somewhere (something about the older display, or older iOS version than on my other test devices?), but it turns out that if you bounce-scroll so the cell goes out of view for a second, when it comes back everything is the right color. Some sort of memory-caching thing?
This blog post from Medium (which, granted, is four years old) talks about how sometimes images might not update properly when you go the dequeue/reuse route with your tableviewcells, and it definitely sounds similar (at least, more similar than any other Google results) to what's happening. I suspect I need to override the prepareForReuse
method for my custom cell class, but I have no idea what I would need to put in there (really, the cell shouldn't be getting reused at all, right? It's initially displaying the wrong content when it's first loaded). The blog post basically just set the image that needed to be re-done to nil
, but that throws errors for me when I try that on my background-color-subview (as expected, the typical "object not found" error because I'm trying to set the background color of a nil object).
Any ideas? Do I have to go in and programmatically build my cell from scratch every cellForRowAtIndexPath? Doesn't that eliminate the whole point of making cells from nibs/xibs, though? And for god's sake, why only on my older iPhone?
question from:
https://stackoverflow.com/questions/65922926/registered-nib-as-custom-tableviewcell-not-displaying-properly-sometimes 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…