美文网首页
iOS Object-C 闭包传递

iOS Object-C 闭包传递

作者: 白色天空729 | 来源:发表于2018-08-21 15:36 被阅读9次

简单模拟写个UIview视图交互,传递闭包。


.h文件

#import <UIKit/UIKit.h>

@interface ZDX : UIView

@property (nonatomic, copy) void (^addPhotoBlock)(void);

@end

.m文件
#import "ZDX.h"

@implementation ZDX


- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        
        
        [self setUserInteractionEnabled:YES];
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addPhoto)];
        [self addGestureRecognizer:tapGes];
        
    }
    return self;
}

- (void)addPhoto {
/// 如果闭包属性不为空,不做处理,为空则传递闭包属性。
    !self.addPhotoBlock ? : self.addPhotoBlock();
}

@end

调用:


    ZDX *zz = [[ZDX alloc] initWithFrame:CGRectMake(0, 100, 100, 100)];
    [self.view addSubview:zz];
    
    zz.addPhotoBlock = ^{
        NSLog(@"sss");
    };

闭包原理了解:
https://www.jianshu.com/p/e82bc3acc2c9

相关文章

网友评论

      本文标题:iOS Object-C 闭包传递

      本文链接:https://www.haomeiwen.com/subject/elljiftx.html