重写AlertView(用block)

@interface AlertView : UIView

@property (nonatomic,copy) void(^block)(UIColor *color);

- (id)initWithAlertView;

- (void)showTwo;

@end

 

 

 

 

自定义View的.m文件

- (id)initWithAlertView

{

    self = [super init];//自定义init方法 就是重写了系统的init方法;

    if (self)

    {

        

        UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];

        btn1.backgroundColor = [UIColor redColor];

        btn1.frame = CGRectMake(5, 100, 40, 25);

        [btn1 addTarget:self action:@selector(btn1Click:) forControlEvents:UIControlEventTouchUpInside];

        [self addSubview:btn1];

        UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];

        btn2.backgroundColor = [UIColor greenColor];

        btn2.frame = CGRectMake(150, 100, 40, 25);

        [btn2 addTarget:self action:@selector(btn2Click:) forControlEvents:UIControlEventTouchUpInside];

        [self addSubview:btn2];

 

    }

    return self;

 

}

- (void)btn1Click:(UIButton *)btn

{

    self.block(btn.backgroundColor);

    [self removeFromSuperview];

}

- (void)btn2Click:(UIButton *)btn

{

    self.block(btn.backgroundColor);

    [self removeFromSuperview];

}

 

 

 

主界面的.m

- (IBAction)buttonClick:(id)sender

{

    AlertView *alertView = [[AlertView alloc] initWithAlertView];

    alertView.backgroundColor = [UIColor grayColor];

    alertView.frame = CGRectMake(100, 100, 200, 130);

//    [alertView initWithAlertView];

    [self.view addSubview:alertView];

    __block ViewController *vc = self;

    alertView.block = ^(UIColor *color){

        vc.view.backgroundColor = color;

    };

//    [alertView showTwo];要不要都行 看情况而定

}

原文地址:https://www.cnblogs.com/dlwj/p/4875872.html