首页 > 代码库 > block对象传递事件

block对象传递事件

MyScrollView.h

@property (nonatomic,assign) NSInteger currentPage;@property (nonatomic,strong) NSInteger (^numberOfPage)(MyScrollView *);@property (nonatomic,strong) UIView *(^scroll)(MyScrollView *,NSInteger);- (void)loadScroll;

 

MyScrollView.m

@interface MyScrollView (){    UIScrollView *_scrollView;}@end@implementation MyScrollView- (instancetype)initWithFrame:(CGRect)frame{    self = [super initWithFrame:frame];    if (self) {               _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];        _scrollView.pagingEnabled = YES;                [self addSubview:_scrollView];    }    return self;}- (void)loadScroll{    [_scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];   //removeFromSuperview:从父视图中移除        NSInteger count = _numberOfPage(self);        CGFloat width = self.frame.size.width;    CGFloat height = self.frame.size.height;    _scrollView.contentSize = CGSizeMake(width * count, height);        for (NSInteger i = 0; i < count; i++) {                UIView *viewer = _scroll(self,i);              viewer.frame = CGRectMake(i * width, 0, width, height);        [_scrollView addSubview:viewer];            }}- (NSInteger)currentPage{    return _scrollView.contentOffset.x / _scrollView.contentSize.width;}- (void)setCurrentPage:(NSInteger)currentPage{    _scrollView.contentOffset = CGPointMake(_scrollView.frame.size.width, 0);    currentPage = currentPage;}@end

ViewController.m

- (void)viewDidLoad {    [super viewDidLoad];        MyScrollView *myScroll = [[MyScrollView alloc] initWithFrame:CGRectMake(0, 50, 320, 160)];      myScroll.numberOfPage = ^(MyScrollView *scrollView){        return 10;    };        myScroll.scroll = ^(MyScrollView *scrollView,NSInteger index){            double value = http://www.mamicode.com/arc4random() % 256;        UIView *view = [[UIView alloc] init];        view.backgroundColor = [UIColor colorWithRed:0.1 green:0.4 blue:value/256 alpha:1];                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];        label.text = [NSString stringWithFormat:@"page: %d",index];        [view addSubview:label];                return view;    };    [self.view addSubview:myScroll];       [myScroll loadScroll];    myScroll.currentPage = 0;    }