LoginSignup
3
5

More than 3 years have passed since last update.

初めてのアプリ SwiftUI自動で消えるAnimationを実装

Posted at

IMG_6413.GIF

アプリの中でよくあるこのような表示ですが、
私のアプリの中にも実装してみたいと思っていました。
結構時間がかかりました。

最初は、Buttonの後ろに.Alertで入れてみましたが、
1秒後に自動に消える機能がなく、AlertのPop画面でユーザに「OK」をクリックしてもらって
消えるしかありません。

そして、プログラミング動画を見てZStackの意味を勘違いしていたのに気づいて、
ZStack Viewで実現できるかもしれないと思って、手を動かして一日くらいやっとう実現できました。

ZStackViewで「画像/文字」のViewを出すのは簡単ですが、
消えてもらうのは難しい、Delay,Disappear,Disable,Removeなど色々KeyWordで検索しても。。。
Animationの中にあるtimingCurveは使えると思っていましたが、勘違いでした。

プログラミング動画(UIKitのAnimationの使い方)を見て、ViewのX/Yの値を変えることによって、
Viewを画面のBottomのさらに下で表示させるか、画面の中で表示させると変えられます。
それを真似してSwift UIの中のOffset(x:,y:)で実装できました!

ソースコードはこんな感じです。
withAnimation{click.wrappedValue = false}は、
withAnimation{click.wrappedValue.toggle()}でもいいですが、
実際に実装する際、他のButtonとViewと支障が出たりするので、
そこら辺をもうちょっと工夫して修正する必要があります。

starHeadView
func alertMessage(click:Binding<Bool>,imageYes:String,imageNo:String,
                  textYes:String,textNo:String,colorYes:Color,colorNo:Color)
                  -> some View {
        HStack{
            if userData.userStarProfiles[starProfileIndex].favorite {
                Image(systemName:imageYes)
                .frame(width: 30, height: 30)
                .foregroundColor(colorYes)
                Text(textYes).fontWeight(.light)
                .onDisappear(perform: {
                    withAnimation{
                        click.wrappedValue = false
                    }
                })
            }else if !userData.userStarProfiles[starProfileIndex].favorite {
                Image(systemName:imageNo)
                .frame(width: 30, height: 30)
                .foregroundColor(colorNo)
                Text(textNo).fontWeight(.light)
                .onDisappear(perform: {
                    withAnimation{
                        click.wrappedValue = false
                    }
                })
            }
        }
        .animation(Animation.easeOut(duration: 1.5)).offset(x:110,y: click.wrappedValue ? 50 : -300)
    }

そして、ZStack Viewの中で上記関数を呼び出す。

starHeadView
alertMessage(click: self.$favoriteClick, imageYes: "heart.fill", imageNo:"heart", textYes: "好き!", textNo: "", colorYes: .pink, colorNo: .gray)
3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5