【SwiftUI】Toggleの使い方

SwiftUI

今回はToggleボタンの使い方について説明します。設定とかでよく使う、オンオフを切り替えるアレです。

環境

  • Xcode13.0
  • 動作はシミュレーターのiPhone13 miniで確認

Toggleの基本的な使い方

基本的には以下のようなコードで使用できます。

Toggle("ラベル", isOn : $isOn)

第1引数にはこのToggleについての説明をするStringを設定します。第2引数には、状態を表すBool型のプロパティを指定します。isOnは@State等で宣言をしておく必要があります。

最もシンプルな実装例は以下になります。

struct ContentView: View {
    @State private var isOn = true
        var body: some View {
            Toggle("トグル", isOn: $isOn)
        }
}

見た目のカスタマイズ

foregroundColorを制定することでテキストの色を、SwitchToggleStyleでボタンの色を変更できます。

struct ContentView: View {
    @State private var isOn = true
        var body: some View {
            Toggle("トグル", isOn: $isOn)
                .foregroundColor(.red)
                .toggleStyle(SwitchToggleStyle(tint: .orange))
        }
}

また、このtoggleStyleで様々な見た目のトグルボタンを実装できるのですが、長くなるのでその方法は次回説明しようと思います。

コメント

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny

タイトルとURLをコピーしました