I want to animate the extending search bar. When I press the search button, I want to extend the search bar to left, and when I close the search text field, to collapse to right.
ToolbarItem(placement: .automatic) {
HStack{
if self.showSearchBar{
HStack{
Image(systemName: "magnifyingglass")
TextField("search from menu", text: self.$txtSearch)
Button{
withAnimation{
self.showSearchBar.toggle()
}
} label:{
Image(systemName: "xmark")
}
}.frame(width: 300, height: 40)
}else{
Button{
withAnimation{
self.showSearchBar.toggle()
}
} label: {
Image(systemName: "magnifyingglass")
}
}
}.padding(self.showSearchBar ? 10 : 0)
.background(Color.white)
.cornerRadius(20)
}
The video of how it is right now: https://files.fm/f/au967z3bh
I know that is possible to extend smoothly from right to left when expanding and left to right when collapsing. How I can add that to my code?
I want similar to this: https://files.fm/u/pgxtzvrk7
If you want it to have animation, you mustn't use
if {} else {}
. Because when the condition was changed, nothing was linked between your views, so it will render a new UI element instead of animating two views.However, using an animation namespace might be the solution to your problem. Read more about
@Namespace
here.Declaration:
put it into the struct which contains your views. Then add the following property:
like this:
Hope this help!