iOS Block

block语法在iOS中应用越来越广,今天大致讲一下Block的用法,主要以回调为主。

大致分几个步骤实现:(以写一个BUtton的回调来说)

1⃣️:声明一个Block和暴露一个接口给外面,并且定义一个property

#import <UIKit/UIKit.h>
//声明一个Block
typedef void (^myBlock)(void);
@interface NewButton : UIButton
@property(nonatomic,strong)myBlock block;
//暴露一个接口给外面
-(void)addTarget:(id)target Andaction:(myBlock)block forControlEvents:(UIControlEvents)controlEvents;
@end
2⃣️:实现方法,并在button被点击的时候触发这个Block。
#import "NewButton.h"

@implementation NewButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    
    return self;
}

-(void)addTarget:(id)target Andaction:(myBlock)block forControlEvents:(UIControlEvents)controlEvents{
    
    
    _block = block;
    [self addTarget:self action:@selector(editBtn:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)editBtn:(id)sender{
    
    _block();
}
3⃣️:调用Button,触发回调。
@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    
    NewButton *button = [NewButton buttonWithType:UIButtonTypeRoundedRect];
    button.backgroundColor = [UIColor greenColor];
    [button setTitle:@"Pressed" forState:UIControlStateNormal];
    [button setFrame:CGRectMake(110, 100, 100, 100)];
    
    [self.view addSubview:button];
    
    [button addTarget:self Andaction:^{
        
        NSLog(@"PRESSED");
    } forControlEvents:UIControlEventTouchUpInside];
}
[self addTarget:self action:@selector(editBtn:) forControlEvents:UIControlEventTouchUpInside];
这个addTarget:后面是Self,而不是Target,这个Mark一下,纠结我20分钟,蛋碎。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值