Search code examples
swiftstringuicollectionviewuilabelnsattributedstring

AttributedString on a CollectionView cell is not displaying string value


I have a UICollectinViewCell with a label set to attributedString.

Inside cellForItem, I cast a simple string to an NSAttributedString so that I can set the UILabel's attributedText property.

The string "Attributed String Text" only appears if I scroll the CollectionView. If I do not scroll, "Label" appears, as that's the text that is set in IB. If I keep the UILabel as plain, the correct text appears just fine.

// cellForItemAt
let string = "Attributed String Text"
let mutableAttributedString = NSAttributedString(string: string)
cell.subName.attributedText = mutableAttributedString

How can I get the attributedText to show without having to scroll the CollectionView?


Solution

  • I figured it out. I believe it may be an Xcode bug. Nothing was wrong with my code. Normal (plain) text UILabel was displaying proper text just fine. When I switched it to attributed UILabel, the text stopped displaying with no other code changes.

    After digging around for a while, I found this thread: Label text in UICollectionViewCell not updating where user Jacksonsox was having a similar issue.

    In Interface Builder, I removed the connection to the UILabel that wasn't updating, deleted the UILabel, re-added a new label, re-connected it, set it to Attributed text, and the text now shows up just fine. Again, no code changes made. Only changes were in IB.

    I hope this helps others who are experiencing similar issues.