0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

swift(アラート機能の実装)~備忘録~

Posted at

iphoneを使っているとよく見るアラートの簡単な実装をしていきたいと思います。
処理の流れとしては

ここを押すボタンを押す

アラートが表示される

OKを押すとアラートが消える

これだけです。

よく見るこうゆうやつです

スクリーンショット 2021-06-13 22.24.05.png

コード全体

//
//  ContentView.swift
//  Shared
//
//  Created by  on 2021/06/13.
//

import SwiftUI

struct ContentView: View {
    @State var isError: Bool = false
    var body: some View {
        Button(action:  {
            //ボタンを押下した時にtrueに変換する。
            isError = true
        }) {
            //ボタンのテキスト
            Text("アラートテスト")
            //trueの時にアラートが表示される。
        }.alert(isPresented : $isError) {
            Alert(title: Text("タイトル"), message: Text("メッセージ文"),
                  primaryButton: .default(Text("OK"), action: {
                    Action()
                  }),
                  //キャンセルボタンの設置
                  secondaryButton: .cancel(Text("キャンセル"), action:{})
            )}
    }
}
func Action(){
    print("OKボタンが選ばれました。")
    
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


1.bool値が格納されるisErroorの宣言

 @State var isError: Bool = false

2.エラーが発生したらtrueにする。

文字通りaction:としてisErrorをtrueにします。

 Button(action:  {
            //ボタンを押下した時にtrueに変換する。
            isError = true
        })

3.デフォルトのテキストを設定します。

以下を設定する事によって、クリックする前のテキストを設定する事ができます。

 //ボタンのテキスト
            Text("アラートテスト")

.alartのモディファイアを利用することでボタン押下時にアラートを表示する事ができます。
primaryButtonでOKの挙動、secondaryButtonでキャンセルの挙動を設定する事ができます。

cancel()で指定する「キャンセル」ボタンはprimaryButtonとsecondaryButtonのどちらで指定しても左側に配置されるようです。

.alert(isPresented : $isError) {
            Alert(title: Text("タイトル"), message: Text("メッセージ文"),
                  primaryButton: .default(Text("OK"), action: {
                    Action()
                  }),
                  //キャンセルボタンの設置
                  secondaryButton: .cancel(Text("キャンセル"), action:{})
            )}

ユーザー定義関数okAction

okボタンを押下した時に実行される関数です。
呼び出し元は .default(Text("OK")) です。

func Action(){
    print("OKボタンが選ばれました。")
    
}

以上です。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?