Ant*_*ton 9 animation text ellipsis swiftui
SwiftUI 具有出色的动画功能,但它处理Text
View 内容更改的方式存在问题。它对文本框的变化进行动画处理,但在没有动画的情况下立即更改文本。因此,当Text
View的内容变长时,动画过渡会导致省略号 (...) 出现,直到文本框达到其全宽。例如,在这个小应用程序中,按下Toggle按钮在较短和较长的文本之间切换:
这是代码:
import SwiftUI
struct ContentView: View {
@State var shortString = true
var body: some View {
VStack {
Text(shortString ? "This is short." : "This is considerably longer.").font(.title)
.animation(.easeInOut(duration:1.0))
Button(action: {self.shortString.toggle()}) {
Text("Toggle").padding()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Run Code Online (Sandbox Code Playgroud)
问题是:如何避免省略号?将一个字符串动画化为两个字符串时,情况更糟,因为短字符串在动画化为较长字符串时完全被省略号替换。
例如,一种可能性是通过添加修饰符,.id(self.shortString ? 0 : 1)
然后添加修饰符,为处于一种或另一种状态的视图分配一个单独的 id .transition()
。这会将文本视为两个不同的视图,之前和之后。不幸的是,在我的情况下,我需要在更改期间移动文本位置,而不同的 id 使动画变得不可能。
我想解决方案是创造性地使用AnimatableData
. 有任何想法吗?
这是可能的方法的演示(粗糙 - 您可以将其重新设计为扩展、修饰符或单独的视图)
使用 Xcode 11.4 / iOS 13.4 测试
struct ContentView: View {
@State var shortString = true
var body: some View {
VStack {
if shortString {
Text("This is short.").font(.title).fixedSize()
.transition(AnyTransition.opacity.animation(.easeInOut(duration:1.0)))
}
if !shortString {
Text("This is considerably longer.").font(.title).fixedSize()
.transition(AnyTransition.opacity.animation(.easeInOut(duration:1.0)))
}
Button(action: {self.shortString.toggle()}) {
Text("Toggle").padding()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
任何缩小动画 gif 尺寸的建议?
I use this way:
- decrease zoom of Preview to 75% (or resize window of Simulator)
- use QuickTimePlayer region-based Screen Recording
- use https://ezgif.com/video-to-gif for converting to GIF
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以在 0.1 秒后将一个或一个字符添加到带有动画的字符串中,但请记住在添加字符时禁用按钮切换,如下所示:
代码:
public struct TextAnimation: View {
public init(){ }
@State var text: String = ""
@State var toggle = false
public var body: some View {
VStack{
Text(text).animation(.spring())
HStack {
Button {
toggle.toggle()
} label: {
Text("Toggle")
}
}.padding()
}.onChange(of: toggle) { toggle in
if toggle {
text = ""
"This is considerably longer.".enumerated().forEach { index, character in
DispatchQueue.main.asyncAfter(deadline: .now() + Double(index) * 0.1) {
text += String(character)
}
}
} else {
text = "This is short."
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3876 次 |
最近记录: |