Wednesday, October 14, 2026
HomeiOS Developmentios - NSTextAttachment photos should not dynamic (mild/darkish mode)

ios – NSTextAttachment photos should not dynamic (mild/darkish mode)

[ad_1]

I’ve a picture that’s dynamic for mild/darkish mode. If I place this picture in a UIImageView, the dynamism works: when the person switches from mild to darkish mode and again, the picture modifications the model of itself that’s displayed. But when I place the identical picture in an NSAttributedString as an NSTextAttachment and show the string in a label, the dynamism doesn’t work: when the person switches from mild to darkish mode, the picture doesn’t change.

To see the issue in motion, paste this code into your viewDidLoad:

    let dimension = CGSize(width: 20, peak: 20)
    let renderer = UIGraphicsImageRenderer(dimension: dimension)
    let image1 = renderer.picture {
        UIColor.crimson.setFill()
        $0.fill(.init(origin: .zero, dimension: dimension))
    }
    let image2 = renderer.picture {
        UIColor.inexperienced.setFill()
        $0.fill(.init(origin: .zero, dimension: dimension))
    }
    let asset = UIImageAsset()
    asset.register(image1, with: .init(userInterfaceStyle: .mild))
    asset.register(image2, with: .init(userInterfaceStyle: .darkish))

    let iv = UIImageView(picture: image1)
    iv.body.origin = .init(x: 100, y: 100)
    self.view.addSubview(iv)

    let textual content = NSMutableAttributedString(string: "Howdy ", attributes: [
        .foregroundColor: UIColor(dynamicProvider: { traits in
            switch traits.userInterfaceStyle {
            case .light: return .red
            case .dark: return .green
            default: return .red
            }
        })
    ])
    let attachment = NSTextAttachment(picture: image1)
    let attachmentCharacter = NSAttributedString(attachment: attachment)
    textual content.append(attachmentCharacter)

    let label = UILabel()
    label.attributedText = textual content
    label.sizeToFit()
    label.body.origin = .init(x: 100, y: 150)
    self.view.addSubview(label)

I’ve intentionally made the textual content font shade dynamic so that you could see that typically shade dynamism does work in an attributed string. However not in an attributed string’s textual content attachment!

So: Is that this actually how iOS behaves, or am I making some mistake in the best way I am configuring the textual content attachment? If that is how iOS behaves, how are you working across the difficulty?

[Note that I cannot use an iOS 15 attachment view provider, because I have to be compatible with iOS 13 and 14. So maybe that would solve the problem, but that solution is not open to me.]

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments