LoginSignup
16
16

More than 5 years have passed since last update.

ViewとViewControllerとの通信にBlocksを使う

Posted at

ViewControllerがなにがしかのカスタムUIViewを生成するケースは様々あると思います。
その中に、ボタンなどが配置されているケースも多いでしょう。
そのときにどうやってタップされた、などのイベントをViewControllerに伝えるべきか。

色々議論があると思いますが、最もシンプルなのはUIView側にBlocksのプロパティを定義して、ViewController側でBlocksを渡してやることでしょうか。

// カスタムUIView

@interface HogeView : UIView

@property (copy, nonatomic) void (^onClick)(NSString *info);

@end
// UIViewController

- (void)viewDidLoad
{
    HogeView *view = [[HogeView alloc] init];
    view.onClick = ^(NSString *info) {
        NSLog(info);
    };
}

循環参照にならないように注意する必要がありますが、delegateなどに比べてシンプルに書けるのが一番のメリットでしょう。

16
16
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
16
16