iOSはButton付きUIViewコントロールをパッケージ化し、エージェントを使用してbuttonにクリックイベントを追加

1801 ワード

カプセル化されたBaseViewhファイル
#import <UIKit/UIKit.h>

@protocol BaseViewButtonDelegete <NSObject>

@optional
//  button       
- (void)buttonBeTouched:(id)sender;

@end

@interface BaseView : UIView

//      
@property (nonatomic, weak) id <BaseViewButtonDelegete> delegate;

@end

カプセル化されたBaseViewmファイル
#import "BaseView.h"

@interface BaseView ()

@property (nonatomic, strong, nullable) UIButton *button;

@end

@implementation BaseView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        self.button.frame = CGRectMake(0, 0, 100, 100);
        self.button.backgroundColor = [UIColor blackColor];
        [self addSubview:self.button];
        [self.button addTarget:self action:@selector(buttonAction) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return self;
}

- (void)buttonAction {
    //  myButtonWillTap    ,       myButtonWillTapf  
    if ([self.delegate respondsToSelector:@selector(buttonBeTouched:)]) {
        [self.delegate buttonBeTouched:self];
    }
}

@end

viewControllerでBaseViewを使用する
#import "ViewController.h"
#import "BaseView.h"

@interface ViewController () <BaseViewButtonDelegete>

@property (nonatomic, strong, nullable) BaseView *baseView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.baseView = [[BaseView alloc] init];
    self.baseView.frame = self.view.frame;
    [self.view addSubview:self.baseView];
    self.baseView.delegate = self;
}

- (void)buttonBeTouched:(id)sender {
    NSLog(@"   ");
}

@end