1
3

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 5 years have passed since last update.

swiftで自前デリゲート

Last updated at Posted at 2016-11-02

swiftで自前のデリゲートを作る方法はObjective-Cのそれとほとんど変わらないという印象です


デリゲートを利用する側(デリゲートで通知する側)

// ①プロトコルの定義(classを継承すること!)
protocol JimaeDelegate:class {

    // ②デリゲートメソッドの宣言
    func JimaeDelegateFunc(hikisuu:String)    
}

class HogemogeView:UIView{

    // ③デリゲートオブジェクト(weakである事!)
    weak var  delegate:ButtonUIViewDelegate? = nil
    
    func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        // ④デリゲート先のメソッドが呼ばれる
        self.delegate?.JimaeDelegateFunc(hikisuu:"タッチされたよ")
    }
}


デリゲートの処理を実装するクラス(デリゲートで通知される側)

// ①デリゲートのプロトコルを実装
class mainViewController: JimaeDelegate {

    // ②デリゲートメソッドを利用する側のクラスのインスタンスを作成
    //(ここではStoryBoardでインスタンスを作成し、IBOutletで変数に紐づけている)
    @IBOutlet weak var haritukeView: HogemogeView!

    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        // ③デリゲートの通知先をこのクラスに設定
        self.haritukeView.delegate = self
    }
    
    // ④デリゲートメソッドの実装
    func JimaeDelegateFunc(hikisuu: String) {
    
        print(hikisuu)
    }

}

◼︎参考にさせていただきました
Swift - delegateを実装する、通知する、通知される
Swift でデリゲートを実装する方法

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?