Search code examples
iosswiftuilabelattributed

Attributed UILabel with Variation resets text after app was sent to background


I'm using an attributed UILabel with Regular x Regular variation. See the following screenshot:

enter image description here

In my view controller I'm setting a text value for the UILabel:

class ViewController: UIViewController
{
    // MARK: - Outlets
    @IBOutlet weak var myLabel: UILabel!

    // MARK: - Life Cycle
    override func viewDidLoad()
    {
        super.viewDidLoad()
        myLabel.text = "THIS IS MY TEXT"
    }
}

When I run the app on device (iOS 13) label shows the right text ("THIS IS MY TEXT"). But if I send the app to background and open it again, the label resets the text to "Label", i.e my text that I set in code is lost. See this video for a better understanding.

On iOS 12 the text cannot be changed in code at all. If I remove the Variation then everything work just fine.


Solution

  • It happens because when the application goes to background, the trait collection is changing, and you made the label text dependent on traits like vertical and horizontal size class.

    You defined two texts for different size classes in storyboard, and you are updating the text once after the view is loaded, but application reacts on changes like it is expected when you are using size classes.

    That's why the application reloads the texts every time the traits collection is changed.

    You should override the method traitCollectionDidChange(_:) in your view controller and update the text there according to the actual trait collection.