import SwiftUI
import RiveRuntime
struct FallbackFontsView: View {
@StateObject private var viewModel = RiveViewModel(
fileName: "fallback_fonts",
fit: .fill
)
private var runBinding: Binding<String> {
Binding {
return self.viewModel.getTextRunValue("ultralight") ?? ""
} set: { text in
try? self.viewModel.setTextRunValue("ultralight", textValue: text)
try? self.viewModel.setTextRunValue("regular", textValue: text)
try? self.viewModel.setTextRunValue("bold", textValue: text)
try? self.viewModel.setTextRunValue("black", textValue: text)
self.viewModel.play()
}
}
var body: some View {
VStack {
viewModel.view().scaledToFit()
Text(
"The included Rive font only contains characters in the set A...G. " +
"Fallback font(s) will be used to draw missing characters with the correct weight."
)
.fixedSize(horizontal: false, vertical: true)
.font(.caption)
.padding()
TextField("Add text with missing characters", text: runBinding)
.textFieldStyle(.roundedBorder)
.padding()
Spacer()
}
.onAppear {
setupFallbackFonts()
}
}
private func setupFallbackFonts() {
// Option 1: Set fallback fonts for all styles
RiveFont.fallbackFonts = [
RiveFallbackFontDescriptor(
design: .default,
weight: .regular,
width: .standard
),
UIFont.systemFont(ofSize: 12, weight: .heavy),
UIFont(name: "Times New Roman", size: 12)!
]
// Option 2: Or use a callback for style-specific fonts
RiveFont.fallbackFontsCallback = { (style: RiveFontStyle) -> [RiveFallbackFontProvider] in
switch style.weight {
case .ultraLight:
return [
RiveFallbackFontDescriptor(weight: .ultraLight),
UIFont.systemFont(ofSize: 20, weight: .ultraLight)
]
case .regular:
return [
RiveFallbackFontDescriptor(),
UIFont.systemFont(ofSize: 20, weight: .regular)
]
case .bold:
return [
RiveFallbackFontDescriptor(weight: .bold),
UIFont.systemFont(ofSize: 20, weight: .bold)
]
case .black:
return [
RiveFallbackFontDescriptor(weight: .black),
UIFont.systemFont(ofSize: 20, weight: .black)
]
default:
return [RiveFallbackFontDescriptor()]
}
}
}
}