跳到主要内容

文本

⚠️ 警告:此功能已弃用,仅支持旧版运行时,不支持当前运行时。请改用数据绑定来替代运行时直接文本运行操作。

概览

文本运行(Text Run)是 Rive 中用于在图形中显示文本的已弃用功能。它允许你在运行时读取和设置文本值。

读取文本

要随时读取给定文本运行的文本值,请在 RiveViewModel 上使用 .getTextRunValue() API:

open func getTextRunValue(_ textRunName: String) -> String?

提供文本运行名称,你将获得返回的 Rive 文本运行值,如果无法查询到文本运行则返回 nil

设置文本

要随时设置给定文本运行的值,请在 RiveViewModel 上使用 .setTextRunValue() API:

open func setTextRunValue(_ textRunName: String, textValue: String) throws

提供文本运行名称和第二个参数 textValue,其中包含你想要设置的新文本值的字符串值。

如果提供的 textRunName Rive 文本运行无法在活动画板上查询到,Rive 将抛出 RiveError.textValueRunError,你可能需要在应用中捕获并优雅地处理此错误。

示例用法

@State private var userInput: String = ""
@State private var rvm = RiveViewModel(fileName: "my-rive-file")

var body: some View {
VStack(spacing: 20) {
Text("Enter text:")
.font(.headline)
TextField("Enter text...", text: $userInput)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
.onChange(of: userInput, perform: { newValue in
if (!newValue.isEmpty) {
try! rvm.setTextRunValue("MyTextRunName", textValue: userInput)
}
})
rvm.view()
}
}

嵌套画板

读取文本

从父画板内的文本运行读取文本类似,你可以使用以下 API 设置组件实例内文本运行的值:

open func getTextRunValue(_ textRunName: String, path: String) -> String?

设置文本

此外,与在父画板内设置文本类似,你可以使用以下 API 读取组件实例内文本运行的值:

open func setTextRunValue(_ textRunName: String, textValue: String, path: String) throws

示例:

@State private var userInput: String = ""
@State private var rvm = RiveViewModel(fileName: "my-rive-file")

var body: some View {
VStack(spacing: 20) {
Text("Enter text:")
.font(.headline)
TextField("Enter text...", text: $userInput)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
.onChange(of: userInput, perform: { newValue in
if (!newValue.isEmpty) {
try! rvm.setTextRunValue("MyTextRunName", textValue: userInput, path: "Artboard/NestedArtboard")
}
})
rvm.view()
}
}

无障碍语义

Rive 文本运行支持辅助功能语义,帮助屏幕阅读器和其他辅助技术更好地理解 Rive 图形中的文本内容。