繁体   English   中英

在 SwiftUI 中平滑更改视图位置

[英]change view location smoothly in SwiftUI

我正在尝试尽可能顺利地更改我的应用程序中的特定视图位置。 更改的条件是通过文本字段更改文本时:

struct ExploreView: View {
    @State var searchText : String = ""
    var body: some View {
        ZStack{
            Color(searchText == "" ? "RedColor" : "BlueColor").edgesIgnoringSafeArea(.top)
            VStack {
                if searchText == "" {
                    Spacer()
                }
                searchBarBottom(searchText: $searchText).shadow(radius: 5).padding(.vertical)
                if searchText != "" {
                    Spacer()
                }
            }
        }
    }
}

这是搜索栏底部:

struct searchBarBottom: View {
    @Binding var searchText : String
    var body: some View {
        HStack{
            HStack{
                if searchText == "" {
                    Image(systemName: "magnifyingglass").foregroundColor(.black)
                }
                TextField("search", text: $searchText)
                if searchText != "" {
                    Button(action: {
                        self.searchText = ""
                    }, label: {
                        Text("cancel")
                    })
                }
            }.padding(.horizontal).frame(height: 36).background(Color("GrayColor")).cornerRadius(5)
            if searchText == "" {
                HStack{
                    NavigationLink(destination: AddSpotView()) {
                        Image(systemName: "plus").resizable().frame(width: 17, height: 17).foregroundColor(.black)
                    }.frame(width: 36, height: 36).background(Color("GrayColor")).cornerRadius(5)
                    NavigationLink(destination: ExploreList()) {
                        Image(systemName: "list.bullet").resizable().frame(width: 17, height: 15).foregroundColor(.black)
                        }.frame(width: 36, height: 36).background(Color("GrayColor")).cornerRadius(5)
                }
            }
            }.padding(.horizontal).frame(width: UIScreen.main.bounds.width/1.1, height: 55).background(Color.white).clipped().shadow(radius: 5).cornerRadius(10)
    }
}

变化如下:

state 当 searchText = "" 在此处输入图像描述

state 当 searchText != "" 在此处输入图像描述

我目前正在使用 Spacer(),因为这是我发现的最简单的方法,但更改非常粗糙,我希望它平滑且易于使用。 关于我如何实现这一目标的任何想法?

谢谢!

只需添加 animation(使用 Xcode 11.4 / iOS 13.4 测试)

    ZStack{
        Color(searchText == "" ? "RedColor" : "BlueColor").edgesIgnoringSafeArea(.top)
        VStack {
            if searchText == "" {
                Spacer()
            }
            searchBarBottom(searchText: $searchText).shadow(radius: 5).padding(.vertical)
            if searchText != "" {
                Spacer()
            }
        }.animation(.default)       // << here !!
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM