Let’s say “The little duck marveled at the sight of the bigger ducks playing in the lake”
How would I italicize only the second instance of the word “duck”?
Let’s say “The little duck marveled at the sight of the bigger ducks playing in the lake”
How would I italicize only the second instance of the word “duck”?
You can write something like this:
var atext: AttributedString = "The little duck marveled at the sight of the bigger ducks playing in the lake"
if let range = atext.range(of: "duck") {
atext[range].font = .body.italic()
}
For a simple example, building off of the answer above, to italicize the second instance of the substring "duck", you could do something like
if let firstRange = atext.range(of: "duck") {
if let secondRange = atext[firstRange.upperBound...].range(of: "duck") {
atext[secondRange].font = .body.italic()
}
}
But as an important side note: in a real-world context, writing code like this does not lend well to localization if the source of your attributed string may be in a different language. If your attributed string is localized text you are displaying to a user, you could use markdown in your .strings
file to indicate specific words that should be emphasized. You can see the "Markdown Support" section of this document for more details.