Target-Action
とは?
イベント発生時に他のオブジェクトにメッセージを送信するのに必要な情報をオブジェクトに保持させるデザインパターン
保持させる情報
aciton selector 呼び出されたメソッドを一意に識別する
target メッセージを受信するオブジェクト。どんなオブジェクトでも良いが、大抵、Control を保持した root view を持つ ViewController
イベント発生時に送信されるメッセージは action message と呼ばれる
アプリケーション上で Control を利用したコードを書くのを容易にしてくれる
Control オブジェクトは UIControl のサブクラス
action selector 及び target は、Control オブジェクトのプロパティ
例えば、スライダーの状態が変化したのに応答する action method を定義できる
action message のターゲットを nil に設定した場合、アプリケーションはターゲットを実行時に解決する
action message は First responder に送信され、その後処理されるまで Responder chain を遡っていく
Action method
sender action message を送信する Control オブジェクト。action message に応答する場合、それをトリガーしたイベントのコンテキストの詳細な情報を取得するために、このオブジェクトに対して問い合わせる
event Control に関連したイベントをトリガーした UIEvent オブジェクト
code:swift
@IBAction func doSomething()
@IBAction func doSomething(sender: UIButton)
@IBAction func doSomething(sender: UIButton, forEvent event: UIEvent)
Target と Action の設定
Control オブジェクトの action 及び target の設定方法は二種類
プログラム上で行う
Interface Builder 上で行う
プログラム上で設定
UIControl に対してaddTarget(_:action:for:) メソッドを呼び出す
このメソッドは、target object 及び action mthod を Control に紐付ける
code:swift
func addTarget(_ target: Any?,
action: Selector,
for controlEvents: UIControl.Event)
https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget
Interface Builder で設定
Control オブジェクトとそのターゲットの紐付けを Interface Builder 上で行なった場合、接続情報は nib ファイルにアーカイブされる
UIKit と AppKit での違い
割愛
https://developer.apple.com/documentation/uikit/uicontrol
https://developer.apple.com/library/archive/documentation/General/Conceptual/Devpedia-CocoaApp/TargetAction.html#//apple_ref/doc/uid/TP40009071-CH3