【问题标题】:How can I animate a SwiftUI view based on the change of a TextEditor's text?如何根据 TextEditor 的文本更改为 SwiftUI 视图设置动画?
【发布时间】:2020-12-09 18:01:17
【问题描述】:

我的应用有一个 SwiftUI 视图,其中包含一个用于收集日志条目的 TextEditor 和一个包含过去条目的列表。

当文本编辑器有一个非空字符串时,会显示一个按钮来处理条目,将其添加到填充列表的数据中,并重置 TextEditor。目前,每当键入文本时,按钮就会突然出现,我希望能够更流畅地制作动画,也许是通过淡化不透明度或放大按钮。但是,我不知道在哪里输入该动画。

   @State var newEntryString = ""
    
    var body: some View {
        NavigationView{
            VStack{
                Text("Create a new log entry.")
                    .padding()
                TextEditor(text: $newEntryString)
                    .cornerRadius(3.0)
                    .padding()
                    .border(Color.gray, width: 1)
                    .frame(minWidth: 0, idealWidth: 100, maxWidth: .infinity, minHeight: 0, idealHeight: 100, maxHeight: 150, alignment: .center)
                                
                HStack {
                    Spacer()
                    if !newEntryString.isEmpty{

                        Button(action: {
                            addEntry()
                        }) {
                            Text("Add Entry")
                        }.buttonStyle(JournalButtonStyle())
                        .animation(Animation.default.speed(1))
                    }
                }
                
                Divider()
                
                List {
                    ForEach(entrys) { item in
                        Text(item.timestamp!, formatter: entryFormatter).font(.footnote)
                            .foregroundColor(.gray)
                            .padding(.bottom, -10)
                        Text((item.entryString!))
                    }
                    .onDelete(perform: deleteEntrys)
                }.onTapGesture {
                    UIApplication.shared.endEditing()
                }

【问题讨论】:

    标签: animation swiftui


    【解决方案1】:

    在容器上使用动画,比如

    HStack {
        Spacer()
        if !newEntryString.isEmpty{
    
            Button(action: {
                addEntry()
            }) {
                Text("Add Entry")
            }.buttonStyle(JournalButtonStyle())
        }
    }.animation(Animation.default.speed(1))     // << here !!
    

    【讨论】:

    • 感谢您让我走上正确的道路。它还帮助我理解我需要将它放置在受动画影响的另一个视图上——更下方的列表。在这两个视图上放置 .animation 修饰符效果很好。
    猜你喜欢
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    相关资源
    最近更新 更多