A SwiftUI based fade-in text animation that works for iOS 15 and above.
It's surprisingly difficult/clumsy to build smooth fade-in text animation in SwiftUI prior to iOS 18 TextRenderer APIs.
This approach uses AttributedString
to achieve a smooth opacity transition over the given time.
It is also designed to be highly customizable so that you can introduce your own logic on how to tokenize the string or interpolate the animation.
import FadeInText
struct MyView: View {
let text: String
var body: some View {
FadeInText(text: text, color: .black, tokenizer: DefaultTokenizer(), interpolator: LinearInterpolator(config: .defaultValue))
}
}
Animation Preview:
fade-in-text-demo.mov
In order to animate with different opacity values for different parts of the text, it would require iOS 17 minimum target.
var body: some View {
var text = Text("")
for chu in chunk {
if #available(iOS 17.0, *) {
text = text + Text(chu).foregroundStyle(.red.opacity(0.5))
} else {
// Fallback on earlier versions
}
}
return text
}
Why not use textrenderer ?
It requires iOS 18 minimum target.