SwiftUI - Misaligned Rectangles when Animating Size of ZStack - swiftui

I'm creating a custom "Disclosure Group" in SwiftUI, that implements a "swipe to delete" kind of function. It works by having two rectangles stacked on top of each other, and the one on the bottom is the red "delete" button you see when you swipe. I also have a boolean value that flags whether or not the component is "expanded," i.e, having larger size. Here is a video of what this looks like:
As you can see, the component expands in size when tapped, and shows a red "delete" button when dragged. But, when unexpanding the component, you can see that part of the delete rectangle shows on the bottom. Below is the implementation, and I'm not sure why the two rectangles don't completely stick together. Does anyone know how I can avoid this glitch?
MRE:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(spacing: 30) {
TestDisclosure()
TestDisclosure()
TestDisclosure()
Spacer()
}
}
}
struct TestDisclosure: View {
#State var expanded: Bool = false
#State var isDeleting: Bool = false
#State var horzdrag: CGFloat = 0 // the horizontal translation of the drag
#State var predictedEnd: CGFloat = 0 // the predicted end translation of the drag
var body: some View {
ZStack {
Rectangle()
.foregroundColor(.red)
label
.clipped()
.offset(x: getOffset(horzdrag: horzdrag))
.animation(.spring(), value: horzdrag)
}
.offset(x: isDeleting ? -400 : 0)
.animation(.spring(), value: isDeleting)
.transition(.move(edge: .leading))
.gesture(
DragGesture()
.onChanged { gesture in
onDragChange(gesture: gesture)
}
.onEnded { _ in
onDragEnd()
}
)
.cornerRadius(15)
.padding(.horizontal)
.onTapGesture {
withAnimation(.spring()) {
expanded.toggle()
}
}
.frame(maxHeight: expanded ? 150 : 85)
.clipped()
}
private var label: some View {
ZStack {
Rectangle()
.foregroundColor(.teal)
VStack {
HStack {
Text("Test")
Spacer()
Text("1 unit")
Text("12 units")
}
.padding(.horizontal)
}
}
}
private func onDragChange(gesture: DragGesture.Value) {
horzdrag = gesture.translation.width
predictedEnd = gesture.predictedEndTranslation.width
}
private func onDragEnd() {
if getOffset(horzdrag: horzdrag) <= -400 {
withAnimation(.spring()) {
isDeleting = true
}
}
horzdrag = .zero
}
// used to calculate how far to move the teal rectangle
private func getOffset(horzdrag: CGFloat) -> CGFloat {
if isDeleting {
return -400
} else if horzdrag < -165 {
return -400
} else if predictedEnd < -60 && horzdrag == 0 {
return -80
} else if predictedEnd < -60 {
return horzdrag
} else if predictedEnd < 50 && horzdrag > 0 && (-80 + horzdrag <= 0) {
return -80 + horzdrag
} else if horzdrag < 0 {
return horzdrag
} else {
return 0
}
}
}

This looks like interference of same animation (spring in this case) applied to different properties, `cause effect is observed when tap (collapse) is applied when drag (offset) is not yet finished.
I'm not sure if this is a bug, but the workaround is to use type of different animations.
Here is a fix - use default instead of spring.
Tested with Xcode 13.3 / iOS 15.4
label
.clipped()
.offset(x: getOffset(horzdrag: horzdrag))
.animation(.default, value: horzdrag) // << here !!

Related

Scrollview conflicting with another scrollview. Swiftui

I have a scrollview who's content expands to fill the screen and stacks in front using the zIndex. The expanded content also has a scrollview for the content inside. I'm literally trying to mimic the Apps Stores "Today" tab with expanding cards and scrollable content inside.
The way I built this though I realized the expanding view is still part of the parent scrollview. As a result the scrollviews are nested and conflict. This was not what I intended.
Im very new to programming. This is the code that basically expands each card. Its pretty basic. A ternary expands the cards. The CardView is the cards content. Attached is a screenshot of what I'm trying to achieve. Need help here. Any info would be great. Been searching the internet for a way to do this right.
struct Media: View {
#EnvironmentObject var vm : ViewModel
#Environment(\.colorScheme) var mode
#State var showCard = false
#State var activeCard = -1
let height = UIScreen.main.bounds.height
var body: some View {
ZStack {
ScrollView (.vertical, showsIndicators: false) {
VStack (alignment:.center, spacing: 30) {
ForEach (vm.cards.indices, id: \.self) { i in
let z=vm.cards[i].z
GeometryReader { geom in
ZStack {
CardView (showCard: $showCard,
activeCard: self.$activeCard,
zValue: $vm.cards[i].z,
i: i,
cards: vm.cards[i])
}//Z
.frame(minHeight: showCard && activeCard == i ? height : nil) //Animates Card Scaling
.padding(.horizontal, showCard && activeCard == i ? 0:20) // Card Padding
.offset(y: i==activeCard ? -geom.frame(in: .global).minY : 0)
} //GEOM
.frame(minHeight: 450)
.zIndex(z)
} //LOOP
} //V
.padding([.bottom, .top])
} //SCROLLVIEW
} //Z
.background(Color("Background Gray"))
}
}
I don't see a problem with the nested ScrollViews, as you put the DetailView on top. I tried to rebuild a simplified version from your code, see below.
BTW: You don't need the outer ZStack.
And at some point you should consider using ForEach over the cards, not over the indices, otherwise you'll run into UI update problems when inserting or deleting cards. I left it for now to stay closer to your original.
struct ContentView: View {
#State var activeCard = -1
let height = UIScreen.main.bounds.height
var body: some View {
ScrollView (.vertical, showsIndicators: false) {
VStack (alignment:.center, spacing: 30) {
ForEach (data.indices, id: \.self) { i in
GeometryReader { geom in
ZStack {
DetailCellView(entry: data[i], isActive: activeCard == i)
.onTapGesture {
if activeCard == i {
activeCard = -1
} else {
activeCard = i
}
}
}//Z
.frame(minHeight: activeCard == i ? height : nil) //Animates Card Scaling
.padding(.horizontal, activeCard == i ? 0 : 20) // Card Padding
.offset(y: activeCard == i ? -geom.frame(in: .global).minY : 0)
} //GEOM
.frame(minHeight: 450)
.zIndex(activeCard == i ? 1 : 0)
.animation(.default, value: activeCard)
} //LOOP
} //V
// .padding([.bottom, .top])
} //SCROLLVIEW
.background(.gray)
}
}
for the while being: a custom outer dragview as workaround ...
struct ContentView: View {
#State var activeCard = -1
let height = UIScreen.main.bounds.height
#State private var offset = CGFloat.zero
#State private var drag = CGFloat.zero
var body: some View {
GeometryReader { geo in
VStack (alignment:.center, spacing: 30) {
ForEach (data.indices, id: \.self) { i in
GeometryReader { geom in
ZStack {
DetailCellView(entry: data[i],
isActive: activeCard == i)
.onTapGesture {
if activeCard == i {
activeCard = -1
} else {
activeCard = i
}
}
}
.frame(minHeight: activeCard == i ? height : nil) //Animates Card Scaling
.padding(.horizontal, activeCard == i ? 0 : 20) // Card Padding
.offset(y: activeCard == i ? -geom.frame(in: .global).minY : 0)
}
.frame(minHeight: 400)
.zIndex(activeCard == i ? 1 : 0)
.animation(.default, value: activeCard)
}
}
// custom drag view
.offset(x: 0 , y: offset + drag)
.background(.gray)
// drag
.gesture(DragGesture()
.onChanged({ value in
drag = value.translation.height
})
.onEnded({ value in
print(offset)
withAnimation(.easeOut) {
offset += value.predictedEndTranslation.height
offset = min(offset, 0)
offset = max(offset, -CGFloat(data.count * (400 + 30)) + height )
drag = 0
}
print(offset)
})
)
}
}
}
So I figured out how to accomplish what I was trying to accomplish.
struct ScrollingHelper: UIViewRepresentable {
let proxy: ScrollingProxy // reference type
func makeUIView(context: Context) -> UIView {
return UIView() // managed by SwiftUI, no overloads
}
func updateUIView(_ uiView: UIView, context: Context) {
proxy.catchScrollView(for: uiView) // here UIView is in view hierarchy
}
}
class ScrollingProxy {
private var scrollView: UIScrollView?
func catchScrollView(for view: UIView) {
if nil == scrollView {
scrollView = view.enclosingScrollView()
}
}
func disableScrolling(_ flag: Bool) {
scrollView?.isScrollEnabled = flag
print(flag)
}
}
extension UIView {
func enclosingScrollView() -> UIScrollView? {
var next: UIView? = self
repeat {
next = next?.superview
if let scrollview = next as? UIScrollView {
return scrollview
}
} while next != nil
return nil
}
}
I used the above code from https://stackoverflow.com/a/60855853/12299030 &
Disable Scrolling in SwiftUI List/Form
Then used in a TapGesture
scrollEnabled = false
scrollProxy.disableScrolling(scrollEnabled)
and used background modifier:
.background(ScrollingHelper(proxy: scrollProxy))

How do I create this effect using SwiftUI

See this gif
What is happening on this gif is: the finger touches the white area on any point on the right part and drags to the left. As the finger drags, these 3 buttons zoom in and appear.
Assuming the buttons zoom from scale = 0 to scale = 1, Does not matter if I release the finger when the scale is at any value bigger than 0. The buttons will zoom to scale 1 automatically.
NOTE: The animation is slow because I am sliding the finger slowly, but the animation follows the finger drag. If I drag left, buttons zoom in, if I drag right, buttons zoom out.
How do I do that with SwiftUI.
I have this code so far for the whole thing.
struct FileManagerPanelListItem: View {
var body: some View {
ZStack{
VStack {
ZStack {
Image("image")
.resizable()
.frame(width: 190, height: 190, alignment: .center)
HStack(alignment:.center){
FileManagerPanelButton("share", Color.white, Color.gray, {})
FileManagerPanelButton("duplicate", Color.white, Color.gray, {})
FileManagerPanelButton("delete", Color.white, Color.red, {})
}
.frame(maxWidth:.infinity)
}
Text("name")
.frame(width:170)
.background(Color.yellow)
.lineLimit(2)
.fixedSize(horizontal: false, vertical: true)
Text("notes")
.frame(width:170)
.background(Color.blue)
.lineLimit(2)
.fixedSize(horizontal: false, vertical: true)
}
}
.frame(maxWidth:240, maxHeight: 240)
}
}
struct FileManagerPanelListItem_Previews: PreviewProvider {
static var previews: some View {
FileManagerPanelListItem()
.previewDevice(PreviewDevice(rawValue: "iPhone 12 Pro Mini"))
}
}
struct FileManagerPanelButton: View {
typealias runOnSelectHandler = ()->Void
private var runOnSelect:runOnSelectHandler?
private var label:String
private var fgColor:Color
private var bgColor:Color
init(_ label: String,
_ fgColor:Color,
_ bgColor:Color,
_ runOnSelect: runOnSelectHandler? ) {
self.label = label
self.fgColor = fgColor
self.bgColor = bgColor
self.runOnSelect = runOnSelect
}
var body: some View {
Button(action: {
runOnSelect?()
}, label: {
Text(label)
.avenir(.ROMAN, size: 16)
.foregroundColor(fgColor)
.frame(height:60)
.frame(maxWidth:.infinity)
})
.frame(maxWidth:.infinity)
.background(bgColor)
.cornerRadius(10)
}
}
any ideas?
Something like this should work:
// view cannot be scaled to zero, so we take some small value near
private let minScale: CGFloat = 0.001
// relative distance from right side of view to open and from left side to close
private let effectiveDragSidePart: CGFloat = 0.1
struct FileManagerPanelListItem: View {
#State
var scale: CGFloat = minScale
#State
var opened = false
var body: some View {
ZStack{
VStack {
ZStack {
Image("profile")
.resizable()
.frame(width: viewWidth, height: 190, alignment: .center)
.gesture(
DragGesture()
.onChanged { value in
guard shouldProcessStartLocation(value.startLocation) else { return }
scale = translationToScale(value.translation)
}
.onEnded { value in
guard shouldProcessStartLocation(value.startLocation) else { return }
withAnimation(.spring()) {
if shouldRestore(value.predictedEndTranslation) {
scale = opened ? 1 : minScale
} else {
scale = opened ? minScale : 1
opened.toggle()
}
}
}
)
HStack(alignment:.center){
FileManagerPanelButton("share", Color.white, Color.gray, {})
.scaleEffect(scale, anchor: .center)
FileManagerPanelButton("duplicate", Color.white, Color.gray, {})
.scaleEffect(scale, anchor: .center)
FileManagerPanelButton("delete", Color.white, Color.red, {})
.scaleEffect(scale, anchor: .center)
}
.frame(maxWidth:.infinity)
}
}
}
.frame(maxWidth:240, maxHeight: 240)
}
private let viewWidth: CGFloat = 190
private func shouldRestore(_ predictedEndTranslation: CGSize) -> Bool {
if opened {
return translationToScale(predictedEndTranslation) == 1
} else {
return translationToScale(predictedEndTranslation) == minScale
}
}
private func shouldProcessStartLocation(_ startLocation: CGPoint) -> Bool {
if opened {
return startLocation.x < viewWidth * effectiveDragSidePart
} else {
return startLocation.x > viewWidth * (1 - effectiveDragSidePart)
}
}
private func translationToScale(_ translation: CGSize) -> CGFloat {
if opened {
return max(0.001, min(1, 1 - translation.width / viewWidth))
} else {
return max(0.001, -translation.width / viewWidth)
}
}
}
You can setup .spring() if the default one is not springy enough

Show hint view in LazyVGrid in SwiftUI

I have lots of button in a LazyVGrid in a ScrollView. I am trying to show a hint view just top of the button I clicked (as like keyboard popup). I don't know how do I catch the position of a ScrollView button. Besides need help to select suitable gesture to complete the task.
Graphical representation...
Here is my code:
struct ShowHint: View {
#State var isPressed: Bool = false
var columns: [GridItem] = Array(repeating: .init(.flexible()), count: 5)
var body: some View {
ZStack{
if isPressed {
ShowOnTopOfButton().zIndex(1)
}
ScrollView(showsIndicators: false) {
LazyVGrid(columns: columns, spacing: 30) {
ForEach(0..<500) { i in
Text("\(i)")
.padding(.vertical, 10)
.frame(maxWidth: .infinity)
.background(Color.red.opacity( isPressed ? 0.5 : 0.9))
.gesture(TapGesture()
//.onStart { _ in isPressed = true } //but there is no property like this!
.onEnded { _ in isPressed = !isPressed }
)
}
}
}
.padding(.top, 50)
.padding(.horizontal, 10)
}
}
}
struct ShowOnTopOfButton: View {
var theS: String = "A"
var body: some View {
VStack {
Text("\(theS)")
.padding(20)
.background(Color.blue)
}
}
}
Here is possible solution - the idea is to show hint view as overlay of tapped element.
Tested with Xcode 12 / iOS 14
struct ShowHint: View {
#State var pressed: Int = -1
var columns: [GridItem] = Array(repeating: .init(.flexible()), count: 5)
var body: some View {
ZStack{
ScrollView(showsIndicators: false) {
LazyVGrid(columns: columns, spacing: 30) {
ForEach(0..<500) { i in
Text("\(i)")
.padding(.vertical, 10)
.frame(maxWidth: .infinity)
.background(Color.red.opacity( pressed == i ? 0.5 : 0.9))
.gesture(TapGesture()
.onEnded { _ in pressed = pressed == i ? -1 : i }
)
.overlay(Group {
if pressed == i {
ShowOnTopOfButton()
.allowsHitTesting(false)
}}
)
}
}
}
.padding(.top, 50)
.padding(.horizontal, 10)
}
}
}

SwiftUI: How to animate a TabView selection?

When tapping a TabView .tabItem in SwiftUI, the destination view associated with the .tabItem changes.
I tried around with putting
.animation(.easeInOut)
.transition(.slide)
as modifiers for the TabView, for the ForEach within, and for the .tabItem - but there is always a hard change of the destination views.
How can I animated that change, for instance, to slide in the selected view, or to cross dissolve it?
I checked Google, but found nothing about that problem...
for me, it works simply, it is a horizontal list, check //2 // 3
TabView(selection: $viewModel.selection.value) {
ForEach(viewModel.dates.indices) { index in
ZStack {
Color.white
horizontalListViewItem(item: viewModel.dates[index])
.tag(index)
}
}
}
.frame(width: UIScreen.main.bounds.width - 160, height: 80)
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
.animation(.easeInOut) // 2
.transition(.slide) // 3
Update Also Check Patrick's comment to this answer below :)
Since .animation is deprecated, use animation with equatable for same.
Try replacing :
.animation(.easeInOut)
.transition(.slide)
with :
#State var tabSelection = 0
// ...
.animation(.easeOut(duration: 0.2), value: tabSelection)
Demo
I have found TabView to be quite limited in terms of what you can do. Some limitations:
custom tab item
animations
So I set out to create a custom tab view. Here's using it with animation
Here's the usage of the custom tab view
struct ContentView: View {
var body: some View {
CustomTabView {
Text("Hello, World!")
.customTabItem {
Text("A")}
.customTag(0)
Text("Hola, mondo!")
.customTabItem { Text("B") }
.customTag(2)
}.animation(.easeInOut)
.transition(.slide)
}
}
Code
And here's the entirety of the custom tab view
typealias TabItem = (tag: Int, tab: AnyView)
class Model: ObservableObject {
#Published var landscape: Bool = false
init(isLandscape: Bool) {
self.landscape = isLandscape // Initial value
NotificationCenter.default.addObserver(self, selector: #selector(onViewWillTransition(notification:)), name: .my_onViewWillTransition, object: nil)
}
#objc func onViewWillTransition(notification: Notification) {
guard let size = notification.userInfo?["size"] as? CGSize else { return }
landscape = size.width > size.height
}
}
extension Notification.Name {
static let my_onViewWillTransition = Notification.Name("CustomUIHostingController_viewWillTransition")
}
class CustomUIHostingController<Content> : UIHostingController<Content> where Content : View {
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
NotificationCenter.default.post(name: .my_onViewWillTransition, object: nil, userInfo: ["size": size])
super.viewWillTransition(to: size, with: coordinator)
}
}
struct CustomTabView<Content>: View where Content: View {
#State private var currentIndex: Int = 0
#EnvironmentObject private var model: Model
let content: () -> Content
init(#ViewBuilder content: #escaping () -> Content) {
self.content = content
}
var body: some View {
GeometryReader { geometry in
return ZStack {
// pages
// onAppear on all pages are called only on initial load
self.pagesInHStack(screenGeometry: geometry)
}
.overlayPreferenceValue(CustomTabItemPreferenceKey.self) { preferences in
// tab bar
return self.createTabBar(screenGeometry: geometry, tabItems: preferences.map {TabItem(tag: $0.tag, tab: $0.item)})
}
}
}
func getTabBarHeight(screenGeometry: GeometryProxy) -> CGFloat {
// https://medium.com/#hacknicity/ipad-navigation-bar-and-toolbar-height-changes-in-ios-12-91c5766809f4
// ipad 50
// iphone && portrait 49
// iphone && portrait && bottom safety 83
// iphone && landscape 32
// iphone && landscape && bottom safety 53
if UIDevice.current.userInterfaceIdiom == .pad {
return 50 + screenGeometry.safeAreaInsets.bottom
} else if UIDevice.current.userInterfaceIdiom == .phone {
if !model.landscape {
return 49 + screenGeometry.safeAreaInsets.bottom
} else {
return 32 + screenGeometry.safeAreaInsets.bottom
}
}
return 50
}
func pagesInHStack(screenGeometry: GeometryProxy) -> some View {
let tabBarHeight = getTabBarHeight(screenGeometry: screenGeometry)
let heightCut = tabBarHeight - screenGeometry.safeAreaInsets.bottom
let spacing: CGFloat = 100 // so pages don't overlap (in case of leading and trailing safetyInset), arbitrary
return HStack(spacing: spacing) {
self.content()
// reduced height, so items don't appear under tha tab bar
.frame(width: screenGeometry.size.width, height: screenGeometry.size.height - heightCut)
// move up to cover the reduced height
// 0.1 for iPhone X's nav bar color to extend to status bar
.offset(y: -heightCut/2 - 0.1)
}
.frame(width: screenGeometry.size.width, height: screenGeometry.size.height, alignment: .leading)
.offset(x: -CGFloat(self.currentIndex) * screenGeometry.size.width + -CGFloat(self.currentIndex) * spacing)
}
func createTabBar(screenGeometry: GeometryProxy, tabItems: [TabItem]) -> some View {
let height = getTabBarHeight(screenGeometry: screenGeometry)
return VStack {
Spacer()
HStack(spacing: screenGeometry.size.width / (CGFloat(tabItems.count + 1) + 0.5)) {
Spacer()
ForEach(0..<tabItems.count, id: \.self) { i in
Group {
Button(action: {
self.currentIndex = i
}) {
tabItems[i].tab
}.foregroundColor(self.currentIndex == i ? .blue : .gray)
}
}
Spacer()
}
// move up from bottom safety inset
.padding(.bottom, screenGeometry.safeAreaInsets.bottom > 0 ? screenGeometry.safeAreaInsets.bottom - 5 : 0 )
.frame(width: screenGeometry.size.width, height: height)
.background(
self.getTabBarBackground(screenGeometry: screenGeometry)
)
}
// move down to cover bottom of new iphones and ipads
.offset(y: screenGeometry.safeAreaInsets.bottom)
}
func getTabBarBackground(screenGeometry: GeometryProxy) -> some View {
return GeometryReader { tabBarGeometry in
self.getBackgrounRectangle(tabBarGeometry: tabBarGeometry)
}
}
func getBackgrounRectangle(tabBarGeometry: GeometryProxy) -> some View {
return VStack {
Rectangle()
.fill(Color.white)
.opacity(0.8)
// border top
// https://www.reddit.com/r/SwiftUI/comments/dehx9t/how_to_add_border_only_to_bottom/
.padding(.top, 0.2)
.background(Color.gray)
.edgesIgnoringSafeArea([.leading, .trailing])
}
}
}
// MARK: - Tab Item Preference
struct CustomTabItemPreferenceData: Equatable {
var tag: Int
let item: AnyView
let stringDescribing: String // to let preference know when the tab item is changed
var badgeNumber: Int // to let preference know when the badgeNumber is changed
static func == (lhs: CustomTabItemPreferenceData, rhs: CustomTabItemPreferenceData) -> Bool {
lhs.tag == rhs.tag && lhs.stringDescribing == rhs.stringDescribing && lhs.badgeNumber == rhs.badgeNumber
}
}
struct CustomTabItemPreferenceKey: PreferenceKey {
typealias Value = [CustomTabItemPreferenceData]
static var defaultValue: [CustomTabItemPreferenceData] = []
static func reduce(value: inout [CustomTabItemPreferenceData], nextValue: () -> [CustomTabItemPreferenceData]) {
value.append(contentsOf: nextValue())
}
}
// TabItem
extension View {
func customTabItem<Content>(#ViewBuilder content: #escaping () -> Content) -> some View where Content: View {
self.preference(key: CustomTabItemPreferenceKey.self, value: [
CustomTabItemPreferenceData(tag: 0, item: AnyView(content()), stringDescribing: String(describing: content()), badgeNumber: 0)
])
}
}
// Tag
extension View {
func customTag(_ tag: Int, badgeNumber: Int = 0) -> some View {
self.transformPreference(CustomTabItemPreferenceKey.self) { (value: inout [CustomTabItemPreferenceData]) in
guard value.count > 0 else { return }
value[0].tag = tag
value[0].badgeNumber = badgeNumber
}
.transformPreference(CustomTabItemPreferenceKey.self) { (value: inout [CustomTabItemPreferenceData]) -> Void in
guard value.count > 0 else { return }
value[0].tag = tag
value[0].badgeNumber = badgeNumber
}
.tag(tag)
}
}
And for the tab view to detect the phone's orientation, here's what you need to add to your SceneDelegate
if let windowScene = scene as? UIWindowScene {
let contentView = ContentView()
.environmentObject(Model(isLandscape: windowScene.interfaceOrientation.isLandscape))
let window = UIWindow(windowScene: windowScene)
window.rootViewController = CustomUIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
I was having this problem myself. There's actually a pretty simple solution. Typically we supply a selection parameter just by using the binding shorthand as $selectedTab. However if we create a Binding explicitly, then we'll have the chance to apply withAnimation closure when updating the value:
#State private var selectedTab = Tabs.firstTab
TabView(
selection: Binding<ModeSwitch.Value>(
get: {
selectedTab
},
set: { targetTab in
withAnimation {
selectedTab = targetTab
}
}
),
content: {
...
}
)
Now, there is a new idea.
swiftUI 2.0 xcode 12.2
tableView(){}.tabViewStyle(PageTabViewStyle())
😄

SwiftUi Transition / Animation

I am new to SwiftUI and have managed to build simple game.
All works except my plan to implement some sort of image animation / transition to introduce the image into the view.
The images are formatted correctly, but too abrupt and hoped to soften the image glow
I have tried by using the animation method, but has not mad a difference.
I hope someone can point me in the right direction.
var body: some View {
NavigationView {
ZStack {
Image("background")
.resizable()
.aspectRatio(contentMode: .fill)
.scaledToFill()
.edgesIgnoringSafeArea(.all)
VStack {
Text("Tap Correct Image")
.font(.headline)
.foregroundColor(Color.blue)
ForEach((0...2), id: \.self) { number in
Image(self.naijaObject[number])
.resizable()
.frame(width: 100, height: 100)
.border(Color.black,width: 1)
.transition(.slide)
.animation(.easeInOut(duration: 1))
.onTapGesture {
self.pictureTapped(number)
}
}
.navigationBarTitle(Text(processCorrectAnswer))
.alert(isPresented: $showAlert) {
Alert(title: Text("\(alertTitle), Your score is \(score)"), dismissButton: .default(Text("Continue")) {
self.askQuestion()
})
}
}//End of VStack
}//End of
} //End of Naviagtion View
} //End of View
//Function to action which object is tapped
func pictureTapped(_ tag: Int) {
if tag == correctAnswer {
score += 1
alertTitle = "Correct"
} else {
score -= 1
alertTitle = "Wrong"
}
showAlert = true
}
//Function to continue the game
func askQuestion() {
naijaObject.shuffle()
correctAnswer = Int.random(in: 0...2)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I think I understand, what you want to achieve, but in future better to present more code. Here I used DispatchQueue.main.asyncAfter(deadline: .now() + 1) where I change the variable showAlert to true. And it works smoothly, hope it'll help you:
struct QuestionGame: View {
#State private var showAlert = false
#State private var score: Int = 0
#State private var correctAnswer = 1
#State private var tapped = false
var body: some View {
NavigationView {
VStack {
Text("Tap Correct Image")
.font(.headline)
ForEach((0...2), id: \.self) { number in
Rectangle()
.frame(width: 100, height: 100)
.foregroundColor(self.tapped && number == self.correctAnswer ? .green : .black) // you can do anything for animation
.animation(.easeInOut(duration: 1.0))
.onTapGesture {
self.pictureTapped(number)
}
}
.navigationBarTitle(Text("answer the question"))
.alert(isPresented: self.$showAlert) {
Alert(title: Text("Your score is \(score)"), dismissButton: .default(Text("Continue")) {
self.askQuestion()
})
}
}
}
}
func pictureTapped(_ tag: Int) {
tapped = true
if tag == correctAnswer {
score += 1
} else {
score -= 1
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.showAlert = true
}
}
//Function to continue the game
func askQuestion() {
tapped = false
showAlert = false
correctAnswer = Int.random(in: 0...2)
}
}
struct QuestionGame_Previews: PreviewProvider {
static var previews: some View {
QuestionGame()
}
}
P.S. and no, I didn't find the way to show alert smoothly. For this case may be better to use ZStack and change the alert (or any other view) opacity from 0 to 1 (with animation), when you tap on image.