アプリケーション開発ポータルサイト
ServerNote.NET
Amazon.co.jpでPC関連商品タイムセール開催中!
カテゴリー【SwiftiPhone/iPadMacOS
【Swift UI】右から登場し右へ消えるアニメーションボタンビュー
POSTED BY
2023-09-18

以下のように、ボタンを押すと右から出現し、そのボタンを押すと右へ消えていくアニメーションサンプル。

コードはこちら。

SwiftContentViewButtons.swiftGitHub Source
//
//  ContentViewButtons.swift
//  MyUITest
//
//  Created by ServerNote.NET on 2023/09/18.
//

import SwiftUI

extension Color {
    init(_ hex: UInt, alpha: Double = 1) {
        self.init(
            .sRGB,
            red: Double((hex >> 16) & 0xFF) / 255,
            green: Double((hex >> 8) & 0xFF) / 255,
            blue: Double(hex & 0xFF) / 255,
            opacity: alpha
        )
    }
}

class G: ObservableObject {
    
    static var shared = G()
    
    @Published var screen_button_width:CGFloat
    @Published var screen_button_height:CGFloat
    
    init() {
        var w = UIScreen.main.bounds.width < UIScreen.main.bounds.height ?
        UIScreen.main.bounds.width:UIScreen.main.bounds.height
        screen_button_width = w / 3 * 2
        screen_button_height = 60
        if screen_button_width > 400 {
            screen_button_width = 400
        }
    }
}

struct ContentViewButtons: View {
    @State private var showButtons = false
    
    var body: some View {
        VStack {
            Button(action: {
                print("Button1 pressed")
                withAnimation {
                    showButtons = true
                }
                
            }) {
                Text("ボタンを右から出現させます")
                    .bold()
                    .padding()
                    .frame(width: G.shared.screen_button_width, height: G.shared.screen_button_height)
                    .foregroundColor(Color.white)
                    .background(
                        LinearGradient(
                            colors: [Color(0xFD79A8), Color(0xFFB5A3)],
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    )
                    .cornerRadius(10)
            }
            if showButtons {
                Button(action: {
                    print("Button2 pressed")
                    withAnimation {
                        showButtons = false
                    }
                }) {
                    Text("このボタンを右へ消します")
                        .bold()
                        .padding()
                        .frame(width: G.shared.screen_button_width, height: G.shared.screen_button_height)
                        .foregroundColor(Color(0x969696))
                        .overlay(
                            RoundedRectangle(cornerRadius: 25)
                                .stroke(Color(0x969696), lineWidth: 3)
                        )
                }
                .transition(.move(edge: .trailing))
            }
        }
    }
}

struct ContentViewButtons_Previews: PreviewProvider {
    static var previews: some View {
        ContentViewButtons()
    }
}

・ボタンの幅はスクリーン幅の2/3としている。ただし最大400px。
・ボタンの高さは60px固定。
・上ボタンは角丸+任意の色から色へのグラデーションを適用。16進数カラー指定のためColorを拡張している。
・下ボタンの表示・非表示を管理するshowButtonの書き換えをwithAnimationで囲うのがポイント。
・右から登場し右へ消えるエフェクトはtransition.move.trailingを指定すればOK。

なお、Xcode上のPreviewProviderでは消えるアニメーションは確認できるが出現するアニメーションが何故か出ない。実機では問題なくアニメーションする。

アニメーションのスピードを指定するには

withAnimation (Animation.linear(duration:0.3)) {
    showButtons = true
}

などとします。durationを低くすればするほど速く、大きくすれば遅くなります。

小さい状態から拡大しながら登場し縮小しながら消えていくには

//.transition(.move(edge: .trailing))
.transition(.scale(scale:0.1))

などと変更します。

登場時または退去時どちらかにだけアニメーションさせたい

アニメーションさせたくないほうのwithAnimationを消します。

//コメントアウトして無効にする
//withAnimation {
    showButtons = false
// }
※本記事は当サイト管理人の個人的な備忘録です。本記事の参照又は付随ソースコード利用後にいかなる損害が発生しても当サイト及び管理人は一切責任を負いません。
※本記事内容の無断転載を禁じます。
【WEBMASTER/管理人】
自営業プログラマーです。お仕事ください!
ご連絡は以下アドレスまでお願いします★

☆ServerNote.NETショッピング↓
ShoppingNote / Amazon.co.jp
☆お仲間ブログ↓
一人社長の不動産業務日誌
【キーワード検索】