天天看點

iOS-建立UIScrollerView(封裝UIScrollerView)

建立繼承于UIView的類WJImageScrollView,代碼實作如下:

WJImageScrollView.h

#import <UIKit/UIKit.h>

/**點選圖檔block,參數目前圖檔索引*/
typedef void(^TapImageViewButtonBlock) (NSInteger imageIndex);

@interface WJImageScrollView : UIView
/**切換圖檔的時間間隔,可選,預設3s*/
@property(nonatomic,assign)CGFloat scrollInterval;
/**頁面銷毀時應該停止定時器,不然無法釋放view 類dealloc時調用
 [timer invalidate]; 
 timer = nil;
 這個方法能解決問題但不明智,有違封裝思想,實際使用中優化 */
@property(nonatomic,strong)NSTimer * timer;

/**
 *  建立輪播器:建立時調用這個方法
 *
 *  @param frame  滾動視圖的frame
 *  @param images 要顯示的圖檔數組
 *
 *  @return 類的對象
 */
+(instancetype)wjImageScrollViewWithFrame:(CGRect)frame
                               WithImages:(NSArray *)images;

/**
 *
 *
 *  @param frame  滾動視圖的frame
 *  @param images 要顯示的圖檔數組
 *
 *  @return 類的對象
 */
-(instancetype)initWithFrame:(CGRect)frame
                  WithIamges:(NSArray *)images;

-(void)addTapEventForImageWithBlock:(TapImageViewButtonBlock)block;
@end      

WJImageScrollView.m

#import "WJImageScrollView.h"

@interface WJImageScrollView ()<UIScrollViewDelegate>
@property(nonatomic,strong)UIScrollView * mainScrollView;

@property(nonatomic,assign)CGFloat widthView;

@property(nonatomic,assign)CGFloat hightView;

@property(nonatomic,strong)NSArray * imagesNameArray;

@property(nonatomic,assign)NSInteger currentPage;

@property(nonatomic,assign)UIViewContentMode  imageViewcontentModel;

@property(nonatomic,strong)UIPageControl * imageViewPageControl;

@property(nonatomic,strong)TapImageViewButtonBlock  block;

@end
@implementation WJImageScrollView

+(instancetype)wjImageScrollViewWithFrame:(CGRect)frame
                               WithImages:(NSArray *)images{
    
    WJImageScrollView * instance = [[WJImageScrollView alloc]
                                    initWithFrame:frame
                                    WithIamges:images];
    return instance;

}

-(instancetype)initWithFrame:(CGRect)frame
                  WithIamges:(NSArray *)images{
    
    self = [super initWithFrame:frame];
    self.translatesAutoresizingMaskIntoConstraints = NO;
    if (self) {
        
        /**擷取滾動視圖的寬度*/
        _widthView = frame.size.width;
        
        /**擷取滾動視圖的高度*/
        _hightView = frame.size.height;
        
        _scrollInterval = 3;
        
        /**目前顯示頁面*/
        _currentPage = 0;
        
        _imageViewPageControl = UIViewContentModeScaleToFill;
        
        self.clipsToBounds = YES;
        
        _imagesNameArray = images;
        
        /**初始化滾動視圖*/
        [self addSubview:self.mainScrollView];
        
        /**建立ImageView*/
        [self createImageView];
        
        /**添加imageViewPageControl*/
        [self addSubview:self.imageViewPageControl];
        
        /**添加timer*/
        [self startTimer];
    }
    return self;
}

-(void)addTapEventForImageWithBlock:(TapImageViewButtonBlock)block{
    if (self.block == nil) {
        if (block != nil) {
            self.block = block;
            [self initImageViewButton];
            
        }
    }
}

-(void)initImageViewButton{
    for (int i = 0; i <= _imagesNameArray.count; i++) {
        
        UIButton * imageBtn = [[UIButton alloc] initWithFrame:CGRectMake(_widthView * i, 0, _widthView, _hightView)];
        imageBtn.tag = 900 + i;
        [imageBtn addTarget:self action:@selector(imageBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.mainScrollView addSubview:imageBtn];
    }
}

#pragma mark - 初始化滾動視圖

-(UIScrollView *)mainScrollView{
    if (!_mainScrollView) {
        _mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, _widthView, _hightView)];
        _mainScrollView.contentSize = CGSizeMake(_widthView * _imagesNameArray.count, _hightView);
        _mainScrollView.pagingEnabled = YES;
        _mainScrollView.showsHorizontalScrollIndicator = NO;
        _mainScrollView.showsVerticalScrollIndicator = NO;
        _mainScrollView.delegate = self;
        _mainScrollView.bounces = NO;
    }
    return _mainScrollView;
}

#pragma mark - 建立UIImageView
-(void)createImageView{
    
    for (int i = 0; i <= _imagesNameArray.count; i++) {
        
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(_widthView * i, 0, _widthView, _hightView)];
        
        if (i == _imagesNameArray.count) {
            
            [self addImageToImageViewWithImageView:imageView WithIndex:0];
            
        }else{
            
            [self addImageToImageViewWithImageView:imageView WithIndex:i];
        }

        [self.mainScrollView addSubview:imageView];

    }
}

#pragma mark - 加載網絡圖檔或者本地圖檔
-(void)addImageToImageViewWithImageView:(UIImageView *)imageView WithIndex:(NSInteger)index{
    [imageView setImage:[UIImage imageNamed:_imagesNameArray[index]]];
}

-(void)imageBtnClick:(UIButton *)btn{
    if (self.block) {
        self.block((btn.tag - 900) == self.imagesNameArray.count? 0:(btn.tag - 900));
    }
}

#pragma mark - 添加PageControl
-(UIPageControl *)imageViewPageControl{
    if (!_imageViewPageControl) {
        _imageViewPageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0,_hightView - 20, _widthView, 20)];
        _imageViewPageControl.numberOfPages = _imagesNameArray.count;
        _imageViewPageControl.pageIndicatorTintColor = [UIColor whiteColor];
        _imageViewPageControl.currentPageIndicatorTintColor = [UIColor redColor];
        _imageViewPageControl.currentPage = _currentPage;
    }
    return _imageViewPageControl;
}


-(void)changeOffset{
    
    if (self.mainScrollView.contentOffset.x / _widthView ==  _imagesNameArray.count ) {
        
        self.imageViewPageControl.currentPage = 0;
        [self.mainScrollView setContentOffset:CGPointMake(0, 0) animated:NO];
        
    }else{
        
        [self.mainScrollView setContentOffset:CGPointMake(self.mainScrollView.contentOffset.x + _widthView, 0) animated:YES];
        
    }
}
#pragma mark - UIScollerView 代理

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    NSInteger currentPageNum = (self.mainScrollView.contentOffset.x / _widthView) ;
    if (self.mainScrollView.contentOffset.x / _widthView == _imagesNameArray.count ) {
        
        self.imageViewPageControl.currentPage = 0;
        [self.mainScrollView setContentOffset:CGPointMake(0, 0) animated:NO];
        
    }else{
        
        self.imageViewPageControl.currentPage = currentPageNum;
        
    }
    
}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    
    [self colseTimer];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)_scrollView{
    
    [self startTimer];
}
#pragma mark --- 開始計時
-(void)startTimer{
    
    if (_timer == nil) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:_scrollInterval target:self selector:@selector(changeOffset) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes];
    }
}

#pragma mark --- 停止計時
-(void)colseTimer
{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

-(void)dealloc{
    NSLog(@"WJImageScrollView釋放");
}
@end      

 使用方法

-(void) addWJImageScrollView{
    
    //擷取要顯示的位置
    CGRect screenFrame = [[UIScreen mainScreen] bounds];
    
    CGRect frame = CGRectMake(10, 160, screenFrame.size.width - 20, 200);
    
    NSArray *imageArray = @[@"001.jpg", @"002.jpg", @"003.jpg", @"004.jpg", @"005.jpg"];
    
    //初始化控件
    self.imageViewDisplay = [WJImageScrollView wjImageScrollViewWithFrame:frame WithImages:imageArray];
    
    //設定輪播時間
    self.imageViewDisplay.scrollInterval = 2;
    
    //把該視圖添加到相應的父視圖上
    [self.view addSubview:self.imageViewDisplay];
    
    [self.imageViewDisplay addTapEventForImageWithBlock:^(NSInteger imageIndex) {
        NSLog(@"點選了------%zd",imageIndex);
    }];
    
}      

能解決問題的不好的方法釋放view

-(void)dealloc{
    NSLog(@"釋放");
    [self.imageViewDisplay.timer invalidate];
    self.imageViewDisplay.timer = nil;
}      

轉載于:https://www.cnblogs.com/WJJ-Dream/p/5786979.html