几个View实现无限可滑动的效果(iOS-OC)

在很多项目中我们都有这样一个需求:就是一个页面上的元素块实现左右滑动(效果就像一个collectionView上面的cell可以左右滑动),但是实际上如果通过collectionView控件实现的话很复杂,一般要考虑很多。而我今天向大家介绍的这种方式就是通过自定义ScrollView的形式,每个cell我这边用自定义view来显示,这也是为了避免用collectionViewCell实现可能会出现的cell重用问题。

废话不多,先上代码:

(首先是自定义view,名字的起的随意SmallLunboView)(.h.m文件如下)

(.h)

#import

#import "TreasureProductInfoModel.h"

@interfaceSmallLunboView :UIView

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UILabel *topLabel;

@property (nonatomic, strong) UILabel *bottomLabel;

@property (nonatomic, strong) UIButton *imgViewBtn;

@property (nonatomic, strong) TreasureProductInfoModel *cellModel;

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

@end

(.m)

#import "SmallLunboView.h"

#import "DMDeviceInfomation.h"

#import "NSString+Tool.h"

#import "Masonry.h"

@interface SmallLunboView ()

{

    CGFloatbigFont;

    CGFloatnormalFont;

    CGFloatsmallFont;

}

@end

@implementation SmallLunboView

- (void)creatUI{

    self.imgViewBtn = [[UIButton alloc]init];

    [self addSubview:self.imgViewBtn];

    //快速投资

    [self.imgViewBtn setImage:[UIImage imageNamed:@"investment"] forState:UIControlStateNormal];

    [self.imgViewBtn addTarget:self action:@selector(imageBtnClick:) forControlEvents:UIControlEventTouchUpInside];

    [self.imgViewBtn setAdjustsImageWhenHighlighted:NO];


    self.topLabel = [[UILabel alloc]init];

    self.topLabel.textColor = COLOR_WORD;

    self.topLabel.backgroundColor = [UIColor whiteColor];

    [self addSubview:self.topLabel];

    self.bottomLabel = [[UILabel alloc]init];

    self.bottomLabel.backgroundColor = [UIColor whiteColor];

    self.bottomLabel.textColor = COLOR_WORD_UN;

    [self addSubview:self.bottomLabel];

    self.titleLabel = [[UILabel alloc]init];

    self.titleLabel.backgroundColor = [UIColor whiteColor];

    self.titleLabel.textColor = [UIColor colorWithRed:255.0f/255.0f green:68.0f/255.0f blue:68.0f/255.0f alpha:1.0];

    [self addSubview:self.titleLabel];

}

- (void)masonryMyUI{

    [self.imgViewBtn mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.left.bottom.right.equalTo(self);

    }];


    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {

        make.center.equalTo(self);

    }];


    [self.topLabel mas_makeConstraints:^(MASConstraintMaker *make) {

        make.centerX.equalTo(self.mas_centerX);

        make.top.mas_equalTo(SCREEN_AUTOMIC_SMALL_HIGHT * 50/1223);

    }];


    [self.bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {

        make.centerX.equalTo(self.mas_centerX);

        make.bottom.mas_equalTo(-SCREEN_AUTOMIC_SMALL_HIGHT * 50/1223);

    }];

}

- (void)setCellModel:(TreasureProductInfoModel*)cellModel{

    _cellModel= cellModel;

    if(!cellModel.term|| [cellModel.termisEqualToString:@""]) {

        self.topLabel.text= cellModel.periods;

    }else{

        self.topLabel.text= [NSStringstringWithFormat:@"%@·%@",cellModel.term,cellModel.periods];

    }

//    self.titleLabel.text = [NSString stringWithFormat:@"%@%%",cellModel.predictAnnualizedRate];


    NSString*str1 = cellModel.predictAnnualizedRate;

    NSString*str2;

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    BOOLisOpen = [defaultsboolForKey:CUSTOMER_EXTEXSION];

    if(!isOpen || !cellModel.rate|| [cellModel.rateisEqualToString:@""] || [cellModel.ratefloatValue] ==0) {

        //选择第一种显示方案

        self.titleLabel.text= str1;

        NSMutableString *mutableStr = [[NSMutableString alloc]init];

        [mutableStrappendString:str1];

        [mutableStrappendString:@"%"];

        NSIntegerlength1 = str1.length;


        NSMutableAttributedString *attributeString = [[NSMutableAttributedString    alloc]initWithString:mutableStr.copy];

        [attributeStringaddAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:bigFont],NSForegroundColorAttributeName:HEXCOLOR(0Xa3a3a3)} range:NSMakeRange(0, length1)];

        [attributeStringaddAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:smallFont],NSForegroundColorAttributeName:HEXCOLOR(0Xa3a3a3)} range:NSMakeRange(length1, 1)];


        self.titleLabel.attributedText= attributeString;

    }else{

        //选择第二种显示方案

        floatnum = [cellModel.ratefloatValue];

        str2 = [NSString stringWithFormat:@"%.2f",num];

        NSIntegerlength1 = str1.length;

        NSIntegerlength2 = str2.length;


        NSMutableString *mutableStr = [[NSMutableString alloc]init];

        [mutableStrappendString:str1];

        [mutableStrappendString:@"+"];

        [mutableStrappendString:str2];

        [mutableStrappendString:@"%"];


        NSMutableAttributedString *attributeString = [[NSMutableAttributedString    alloc]initWithString:mutableStr.copy];

        [attributeStringaddAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:bigFont],NSForegroundColorAttributeName:HEXCOLOR(0Xa3a3a3)} range:NSMakeRange(0, length1)];


        [attributeStringaddAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:normalFont],NSForegroundColorAttributeName:HEXCOLOR(0Xa3a3a3)} range:NSMakeRange(length1, 1)];


        [attributeStringaddAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:bigFont],NSForegroundColorAttributeName:HEXCOLOR(0Xa3a3a3)} range:NSMakeRange(1+length1, length2)];


        [attributeStringaddAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:smallFont],NSForegroundColorAttributeName:HEXCOLOR(0Xa3a3a3)} range:NSMakeRange(1+length1 + length2, 1)];


        self.titleLabel.attributedText= attributeString;

    }



    floatplanRaise = cellModel.planRaiseAmount.floatValue;

    if(!cellModel.planRaiseAmount|| [cellModel.planRaiseAmountisEqualToString:@""] || planRaise <=0) {

        self.titleLabel.textColor=HEXCOLOR(0X9b9b9b);

    }else{

        self.titleLabel.textColor = [UIColor colorWithRed:255.0f/255.0f green:68.0f/255.0f blue:68.0f/255.0f alpha:1.0];

    }   

    self.bottomLabel.text = @"预期年化收益";

}

- (instancetype)initWithFrame:(CGRect)frame {

    self= [superinitWithFrame: frame];

    if(self) {

        [self getSubUIFont];

        [selfcreatUI];

    }

    return self;

}

- (void)getSubUIFont {

    NSString *_phoneType = [DMDeviceInfomation phoneType];

    if(iPhone4s||iPhone4|| [_phoneTypeisEqualToString:@"iPhone 4s"] ||iPad3_4_mini2_air||iPad1_2_mini||iPadPro|| [_phoneTypehasPrefix:@"iPad"]){

        bigFont=20;

        normalFont=13;

        smallFont=10;

    }elseif(iPhone5||iPhone5s  ||[_phoneTypeisEqualToString:@"iPhone 5"] || [_phoneTypeisEqualToString:@"iPhone 5c"]|| [_phoneTypeisEqualToString:@"iPhone 5s"] || [_phoneTypeisEqualToString:@"iPhone SE"]){

        bigFont=20;

        normalFont=13;

        smallFont=10;

    }elseif(iPhone6|| [_phoneTypeisEqualToString:@"iPhone 6"] || [_phoneTypeisEqualToString:@"iPhone 6s"]){

        bigFont=21;

        normalFont=14;

        smallFont=12;

    }else{

        bigFont=21;

        normalFont=14;

        smallFont=12;

    }

}

- (void)layoutSubviews {

    [super layoutSubviews];

    self.titleLabel.textAlignment = NSTextAlignmentCenter;

    self.topLabel.font = [UIFont systemFontOfSize:normalFont+1];

    self.bottomLabel.font = [UIFont systemFontOfSize:smallFont];

    [self masonryMyUI];

}

- (void)imageBtnClick:(id)sender {

    self.imageBtnCLickblock();

}

@end

(然后是自定义ScrollView,名称UICustomSmallLunboView)(.h.m文件如下)

(.h)

#import

@interfaceUICustomSmallLunboView :UIView

//{

//    NSMutableArray *imageArray;//存放图片

//    NSInteger nowPageNumber;

//}

@property(nonatomic,strong) UIScrollView *myScrollView;

@property (nonatomic, strong) NSMutableArray *imageArray;

@property(nonatomic,copy)void(^imgBtnClickBlock)(NSIntegerwhichImagePage);//点击图片,显示详情

/* 刷新数据 */

- (void)reloadLectureDataArray:(NSArray*)imageUrlArr;

@end

(.m)

#import "UICustomSmallLunboView.h"

#import

#import "UIImageView+WebCache.h"

#import "UIColor+Extension.h"

#import "SmallLunboView.h"

#import "AppDelegate.h"

/* 图片的坐标大小  */

#define imageCellW        SCREEN_WIDTH/3//cell的宽

#define imageCellH        SCREEN_HIGHT_SCALE *250//cell的高

#define imageCellWW        SCREEN_WIDTH *0.395//cell的宽

#define imageCellHH        SCREEN_WIDTH *0.253//cell的高

@implementationUICustomSmallLunboView

staticconstNSUIntegerstartTag =11011;//初始tag值

- (UIScrollView*)myScrollView {


    if (_myScrollView == nil) {


        _myScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.frame.size.height)];    //scrollView的大小

        _myScrollView.showsVerticalScrollIndicator=NO;

        _myScrollView.showsHorizontalScrollIndicator=NO;//隐藏垂直和水平显示条

        _myScrollView.delegate=self;


        if(self.imageArray.count>3) {

             [_myScrollView setContentSize:CGSizeMake(imageCellW*(self.imageArray.count+1)*2, imageCellH)];

        }

        [_myScrollView scrollRectToVisible:CGRectMake(imageCellW, 0, SCREEN_WIDTH, self.frame.size.height) animated:NO];

        [self addSubview:_myScrollView];

    }

    return _myScrollView;

}

/* 初始化 */

- (id)initWithFrame:(CGRect)frame

{

    if(self= [superinitWithFrame:frame])

    {

        self.imageArray = [[NSMutableArray alloc] init];

    }

    return self;

}

/* 根据数据源,布局页面*/

- (void)reloadLectureDataArray:(NSArray*)imageUrlArr {


    if(self.imageArray.count>0)

    {

        [self.imageArray removeAllObjects];

    }


    /* 对数据的各种情况进行判断 */

    if(imageUrlArr ==nil)

    {

        NSDictionary *picDic = [NSDictionary dictionaryWithObjectsAndKeys:

                                @"",@"url",

                                nil];

        NSArray*picArr = [NSArrayarrayWithObject:picDic];

        [self.imageArrayaddObjectsFromArray:picArr];

    }

    else

    {

        [self.imageArrayaddObjectsFromArray:imageUrlArr];

    }


    /* 创建scroller和pageControl */

    [self configScrollView];


}

/* 创建scroller*/

-(void)configScrollView {


    /* 拖动属性 */

    if(self.imageArray.count<1) {


        self.myScrollView.scrollEnabled=NO;

    }else{


        self.myScrollView.scrollEnabled=YES;

    }




        [self createSmallLunboView:CGRectMake(0, 0, imageCellW, imageCellH) No:self.imageArray.count -1];

        /*2、添加数组图片,由于图片较小,放两遍*/


    if(self.imageArray.count>3) {

        for(intj =0; j <2; j++) {

            for(inti=0; i<[self.imageArraycount]; i++) {

                [selfcreateSmallLunboView:CGRectMake(imageCellW+ (imageCellW*self.imageArray.count* j) +imageCellW* i,0,imageCellW,imageCellH)No:i];

            }

        }

    }else{

        for(inti=0; i<[self.imageArraycount]; i++) {

            [selfcreateSmallLunboView:CGRectMake(imageCellW* i,0,imageCellW,imageCellH)No:i];

        }

    }

        /*3、最后再把数组第一张图片加上去*/


        [self createSmallLunboView:CGRectMake(imageCellW*(self.imageArray.count*2+1), 0, imageCellW, imageCellH) No:0];

}

- (void)createSmallLunboView:(CGRect)rect No:(NSInteger)num {

        SmallLunboView*subView = [[SmallLunboViewalloc]initWithFrame:rect];


        TreasureProductInfoModel *imgModel = [[TreasureProductInfoModel alloc]init];

        if(num < [self.imageArraycount]) {


            imgModel = [self.imageArrayobjectAtIndex:num];

        }

    subView.cellModel= imgModel;

        __weaktypeof(self)weakSelf  =self;

        [subViewsetImageBtnCLickblock:^() {


            weakSelf.imgBtnClickBlock(num);

        }];

        [self.myScrollViewaddSubview:subView];

}

#pragma UIScrollView delegate

-(void)scrollViewDidScroll:(UIScrollView*)scrollView

{

    if(self.imageArray.count<1) {

        return;

    }

    //    CGFloat decelerate = scrollView.decelerationRate;

    CGFloatcurrentOffsetX = scrollView.contentOffset.x;


        if(currentOffsetX <=10.0) {

            if(self.imageArray.count>3) {

                [_myScrollViewscrollRectToVisible:CGRectMake(imageCellW* (self.imageArray.count*2+2)+currentOffsetX,0,SCREEN_WIDTH,self.frame.size.height)animated:NO];

            }


        }elseif(currentOffsetX >=imageCellW* (self.imageArray.count*2+2) -SCREEN_WIDTH-10) {



            if(self.imageArray.count>2) {

            [_myScrollView scrollRectToVisible:CGRectMake(imageCellW * (self.imageArray.count + 2)-SCREEN_WIDTH - 10, 0, SCREEN_WIDTH, self.frame.size.height) animated:NO];

            }


        }

}

@end

实现这样的效果就是利用这两个文件实现的,如果你要显示的“cell”不一样,你可以修改这里的SmallLunboView文件,如果你想一个页面显示至少四个或者其他任何数量“cell”你可以修改里面的#define imageCellW        SCREEN_WIDTH/3这个宏,“3”替换成你想要的个数就可以了。我这里写的有点多,是因为我做了字体的适配。我这里控制关键数是“3”,就是当三个以内我是不让控件无限滑动的。只有当超过三个的才让其无限滑动,当然这个“3”也可以更改。

如果大家还有什么疑问可以加我的微信:Xpc1314520xpc.这个控件我感觉还不错,但是肯定还可以优化的,如果有更好的建议,欢迎置信。

你可能感兴趣的:(几个View实现无限可滑动的效果(iOS-OC))