元柔道整復師エンジニアBlog

- 元柔道整復師エンジニアBlog -

『 エンジニアをリングする。』

【Swift】@IBActionのsender(Any型)からUIButtonの重複タップを防止する。

目的

  • StoryBoard上のあるUIButtonに接続された@IBActionsender(Any型)から重複タップを防止したい。
  • @IBActionのみ接続されたUIButtonの重複タップを防止したい。

前提条件

  1. StroryBoard側には、対象のUIButtonが配置されている。
  2. コード側では、1.のUIButtonが@IBActiononClickButton(sender: Any)にのみ接続されている。
  3. StoryBoard上への変更は加えない。
class ViewController: UIViewController {
    
    // UIButton押下時の処理
    @IBAction func onClickBtn(_ sender: Any) {
        
        // ここで重複タップを防止させたい
    }

}

方法

  • @IBActionのsenderからUIButton属性を取得する。
    →この場合、senderはAny型のためUIBUttonへキャストする。

  • UIButton属性を取得後、Enabledステータスをfalseに変更する。
    →UIButtonを非活性にする。

  • UIButton押下時に、Enabledステータスをtrueに戻す。
    →UIButtonを活性にもどす。

class ViewController: UIViewController {
    
    // UIButton押下時の処理
    @IBAction func onClickBtn(_ sender: Any) {
        
        // UIButtonを非活性にする
        let targetButton = sender as! UIButton
        targetButton.isEnabled = false
        
        // 何らかの処理(アニメーションなど)
        ・
        ・
        ・
        
        // メイン処理後に、UIButtonを活性に戻す
        targetButton.isEnabled = true
    }

}