Seb*_*ian 2 swiftui swiftui-animation
我正在创建这个动画,想知道是否有办法让它变得更有趣。
这是代码:
import SwiftUI
struct TypewriterView: View {
let text: String
@State private var animatedText = ""
var body: some View {
Text(animatedText)
.font(.title)
.padding()
.onAppear {
animateText()
}
}
private func animateText() {
for (index, character) in text.enumerated() {
DispatchQueue.main.asyncAfter(deadline: .now() + Double(index) * 0.05) {
withAnimation {
animatedText += String(character)
}
}
}
}
}
// Usage example
struct ContentView: View {
var body: some View {
TypewriterView(text: "Hello, Twitter! This is a typewriter animation.")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Run Code Online (Sandbox Code Playgroud)
withAnimation也许我应该在...中设置一个动画
有什么想法吗?
你想要的恰恰相反。你不想要动画。这导致了两个州之间的融合。您只想添加字符。我推荐这种方法,用 async/await 替换 GCD:
var body: some View {
Text(animatedText)
.font(.title)
.padding()
.task { await animateText() } // Use .task to create async context
}
private func animateText() async {
for character in text {
animatedText.append(character)
// Use `.sleep` to separate the updates rather than `asyncAfter`
try! await Task.sleep(for: .milliseconds(75))
}
}
Run Code Online (Sandbox Code Playgroud)
我看到了一个不相关的问题,即文本在自动换行时改变了其布局的想法。当文本删除最后一个单词时,“a”将与“打字机”一起放在第二行。当第三个单词添加到该行时,视图会调整大小,并且“a”向上移动一行,这打破了“打字机”错觉。我还没有找到一个好的解决方案(但它与动画问题分开)。
为了解决文本重新格式化的问题,创建一个正确长度的空格字符串,然后交换字母似乎确实有效。.monospaced()如果添加到文本中,效果会更好,这样可以更好地匹配打字机的外观,但这不是必需的。
var body: some View {
Text(animatedText)
.font(.title)
.monospaced() // If desired
.padding()
.task { await animateText() }
.onTapGesture {
// makes testing it easier
animatedText = ""
Task { await animateText() }
}
}
private func animateText() async {
var characters = Array(repeating: Character(" "),
count: text.count)
for (index, character) in zip(characters.indices, text) {
characters[index] = character
animatedText = String(characters)
try! await Task.sleep(for: .milliseconds(50))
}
}
Run Code Online (Sandbox Code Playgroud)
换行还是有点别扭,因为它只有超过行宽才会换行,所以它更像是一个文字处理器而不是打字机,但对于少量代码来说这是一个相当不错的效果。
我对此做了更多思考,一个可能更好的方法是使所有文本清晰,然后逐步删除该属性。这样就只有一个布局步骤。这是一个更新版本,它可以执行此操作,并在文本更改时重新启动动画。
struct TypewriterView: View {
var text: String
var typingDelay: Duration = .milliseconds(50)
@State private var animatedText: AttributedString = ""
@State private var typingTask: Task<Void, Error>?
var body: some View {
Text(animatedText)
.onChange(of: text) { _ in animateText() }
.onAppear() { animateText() }
}
private func animateText() {
typingTask?.cancel()
typingTask = Task {
let defaultAttributes = AttributeContainer()
animatedText = AttributedString(text,
attributes: defaultAttributes.foregroundColor(.clear)
)
var index = animatedText.startIndex
while index < animatedText.endIndex {
try Task.checkCancellation()
// Update the style
animatedText[animatedText.startIndex...index]
.setAttributes(defaultAttributes)
// Wait
try await Task.sleep(for: typingDelay)
// Advance the index, character by character
index = animatedText.index(afterCharacter: index)
}
}
}
}
// Usage example
struct ContentView: View {
@State var text = "Hello, Twitter! This is a typewriter animation."
var body: some View {
TypewriterView(text: text)
.font(.title)
.padding()
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
532 次 |
| 最近记录: |