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 = 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;    
}

 

转载于:https://www.cnblogs.com/annboo/p/3927083.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值