malcommac / SwiftRichString

👩‍🎨 Elegant Attributed String composition in Swift sauce
MIT License
3.1k stars 211 forks source link

DynamicType not working in a UITableViewCell that reuses a style #123

Open CraigSiemens opened 4 years ago

CraigSiemens commented 4 years ago

I'm running into an issue where if I reuse a Style with UITableViewCells, it uses the correct size the first time it's shown based on the content size category, then if the content size category changes it doesn't resize until the app is relaunched.

If I change to set the font directly on the label it resizes when the content size category changes.

If I create a new instance of the Style for each cell it also resizes when the content size category changes.

Here is the simplest version I could some up with to reproduce the issue. Throw this in a UITableViewController and it should show the issue when you change the content size category using either the Accessibility Inspector or the Environment Overrides in Xcode..

    let headerStyle = Style {
        $0.font = UIFont.preferredFont(forTextStyle: .body)
        $0.dynamicText = DynamicText()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
        cell.textLabel?.adjustsFontForContentSizeCategory = true

        // Doesn't work
        cell.textLabel?.style = headerStyle
        cell.textLabel?.styledText = "\(indexPath)"

        // Works fine
//        cell.textLabel?.font = UIFont.preferredFont(forTextStyle: .body)
//        cell.textLabel?.text = "\(indexPath)"

        // Also works fine
//        cell.textLabel?.style = Style {
//            $0.font = UIFont.preferredFont(forTextStyle: .body)
//            $0.dynamicText = DynamicText()
//        }
//        cell.textLabel?.styledText = "\(indexPath)"

        return cell
    }