IOS学习 Block语法的使用:Button、AlertView监听方法改写

@implementation HomeViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    

    BlockButton *btn = [[BlockButton alloc]initWithFrame:CGRectMake(50, 50, 100, 40)];

    [btn setTitle:@"按钮" forState:UIControlStateNormal];

    btn.backgroundColor = [UIColor purpleColor];

//    btn.block = ^(BlockButton *btn){

//        NSLog(@"打印");

//    };

    [self.view addSubview:btn];

    

    btn.block = ^(BlockButton *btn)

    {

        BlockUIAlertView *alertView = [[BlockUIAlertView alloc]initWithTitle:@"提示" message:@"是否继续?" cancelButtonTitle:@"取消" otherButtonTitles:@"继续" buttonBlock:^(NSInteger index)

        {

            if (index == 0)

            {

                NSLog(@"取消");

            }else if (index == 1){

                NSLog(@"继续");

            }

        }];

        [alertView show];

    };

}



#import <UIKit/UIKit.h>

@class BlockButton;


typedef void(^TouchButton)(BlockButton *);


@interface BlockButton : UIButton


//Block 要用copy定义

@property (nonatomic,copy) TouchButton block;


@end



@implementation BlockButton


//复写初始化方法

-(id)initWithFrame:(CGRect)frame{

    self = [super initWithFrame:frame];

    if (self) {

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

    }

    return self;

}


-(void)clickAction{

    //两种方式调用

//    self.block(self);

    _block(self);

}


@end




#import <UIKit/UIKit.h>


typedef void(^ButtonBlock)(NSInteger);


@interface BlockUIAlertView : UIAlertView


@property (nonatomic,copy)ButtonBlock block;


- (instancetype)initWithTitle:(nullable NSString *)title

                      message:(nullable NSString *)message

            cancelButtonTitle:(nullable NSString *)cancelButtonTitle

            otherButtonTitles:(nullable NSString *)otherButtonTitles

                  buttonBlock:(nullable ButtonBlock)block;


@end



@implementation BlockUIAlertView


- (instancetype)initWithTitle:(nullable NSString *)title

                      message:(nullable NSString *)message

            cancelButtonTitle:(nullable NSString *)cancelButtonTitle

            otherButtonTitles:(nullable NSString *)otherButtonTitles

                  buttonBlock:(nullable ButtonBlock)block{

    self = [super initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil];

    if (self != nil) {

        self.block = block;

    }

    return self;

}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    _block(buttonIndex);

}


@end



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值