u16suzuの blog

日々学んだことのメモブログです。

カスタムビューの動作をビューコントローラ側で設定する

iQONのView構成紹介 14ページ目

http://www.slideshare.net/ararajp/vasilyretty?ref=http://tech.vasily.jp/2013/09/ios_iqon_view/

のスパイクプロジェクトをつくってみた.

カスタムビューを作ったときにカスタムビューのなかではなく

それを使うビューコントローラの側でアクションを設定する.

と言うことをやるスパイク.

嬉しい点はカスタムビューの再利用性が高まること.

見た目は同じだけどアクションが異なると言うときに再利用できる.

ViewController

  • 実装ファイル
- (void)viewDidLoad
{
    [super viewDidLoad];
    // CustomView 1
    CustomView *cv =
        [[CustomView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    CGPoint center = self.view.center;
    center.y = 150;
    cv.center = center;
    cv.buttonPressedBlock = ^(void){
        UIAlertView *al =
        [[UIAlertView alloc]initWithTitle:@"Block alert1"
                                  message:nil
                                 delegate:self
                        cancelButtonTitle:@"OK"
                        otherButtonTitles:nil];
        [al show];
        return ;
    };    
    [self.view addSubview:cv];
    

    // CustomView 2
    CustomView *cv2 = [[CustomView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    cv2.center = self.view.center;
    cv2.buttonPressedBlock = ^(void){
        UIAlertView *al =
        [[UIAlertView alloc]initWithTitle:@"Block alert2"
                                  message:nil
                                 delegate:self
                        cancelButtonTitle:@"OK"
                        otherButtonTitles: nil];
        [al show];
    };
    [self.view addSubview:cv2];
}

CustomView

  • ヘッダー
//  CustomView.h
#import <UIKit/UIKit.h>
typedef void(^MyCustomBlockType)(void);

@interface CustomView : UIView
@property (nonatomic, copy) MyCustomBlockType buttonPressedBlock;
@end

  • 実装ファイル
//  CustomView.m

#import "CustomView.h"

@interface CustomView ()
@end

@implementation CustomView
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setTitle:@"Btn" forState:UIControlStateNormal];
        button.frame = CGRectMake(0,0, 50,50);
        button.center = self.center;
        [button addTarget:self action:@selector(pushBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
    }
    return self;
}

- (void)pushBtn:(id)sender{
    self.buttonPressedBlock();
}

@end

github: https://github.com/u16suzu/setupBlockInViewControllerSpike