iOS封装Card视图

很多小伙伴做开发的时候都会用到卡片视图 如下面:

Card.gif

在这里我列举全部的实现代码,需要的朋友可以参考,也方便下自己下次使用。下面是完整的代码。

HJTCardView.h
#import <UIKit/UIKit.h>

typedef NS_ENUM(NSUInteger, HJTCardViewEffect) {
    HJTCardViewEffectNone,
    HJTCardViewEffectTranslation,
    HJTCardViewEffectDepth,
    HJTCardViewEffectCarousel,
    HJTCardViewEffectCards
};

@interface HJTCardView : UIScrollView

@property (nonatomic) HJTCardViewEffect effect;

@property (nonatomic) CGFloat angleRatio;

@property (nonatomic) CGFloat rotationX;
@property (nonatomic) CGFloat rotationY;
@property (nonatomic) CGFloat rotationZ;

@property (nonatomic) CGFloat translateX;
@property (nonatomic) CGFloat translateY;

- (NSUInteger)currentPage;

- (void)loadNextPage:(BOOL)animated;
- (void)loadPreviousPage:(BOOL)animated;
- (void)loadPageIndex:(NSUInteger)index animated:(BOOL)animated;

@end


HJTCardView.m
#import "HJTCardView.h"

#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))
#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)

@implementation HJTCardView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(!self){
        return nil;
    }
    
    [self commonInit];
    
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(!self){
        return nil;
    }
    
    [self commonInit];
    
    return self;
}

- (void)commonInit
{
    self.pagingEnabled = YES;
    self.clipsToBounds = NO;
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator = NO;
    
    self.effect = HJTCardViewEffectNone;
}

- (void)setEffect:(HJTCardViewEffect)effect
{
    self->_effect = effect;
    
    switch (effect) {
        case HJTCardViewEffectTranslation:
            self.angleRatio = 0.;
            
            self.rotationX = 0.;
            self.rotationY = 0.;
            self.rotationZ = 0.;
            
            self.translateX = .25;
            self.translateY = .25;
            break;
        case HJTCardViewEffectDepth:
            self.angleRatio = .5;
            
            self.rotationX = -1.;
            self.rotationY = 0.;
            self.rotationZ = 0.;
            
            self.translateX = .25;
            self.translateY = 0.;
            break;
        case HJTCardViewEffectCarousel:
            self.angleRatio = .5;
            
            self.rotationX = -1.;
            self.rotationY = 0.;
            self.rotationZ = 0.;
            
            self.translateX = .25;
            self.translateY = .25;
            break;
        case HJTCardViewEffectCards:
            self.angleRatio = .5;
            
            self.rotationX = -1.;
            self.rotationY = -1.;
            self.rotationZ = 0.;
            
            self.translateX = .25;
            self.translateY = .25;
            break;
        default:
            self.angleRatio = 0.;
            
            self.rotationX = 0.;
            self.rotationY = 0.;
            self.rotationZ = 0.;
            
            self.translateX = 0.;
            self.translateY = 0.;
            break;
    }
    
    [self setNeedsDisplay];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat contentOffsetX = self.contentOffset.x;
    //CGFloat contentOffsetY = self.contentOffset.y;
    
    for(UIView *view in self.subviews){
        CATransform3D t1 = view.layer.transform; // Hack for avoid visual bug
        view.layer.transform = CATransform3DIdentity;
        
        CGFloat distanceFromCenterX = view.frame.origin.x - contentOffsetX;
//        CGFloat distanceFromCenterY = view.frame.origin.y - contentOffsetY;
        
        view.layer.transform = t1;
                
        distanceFromCenterX = distanceFromCenterX * 100. / CGRectGetWidth(self.frame);
//        distanceFromCenterY = distanceFromCenterY * 100. / CGRectGetHeight(self.frame);
        
        CGFloat angle = distanceFromCenterX * self.angleRatio;
        
        CGFloat offset = distanceFromCenterX;
        CGFloat translateX = (CGRectGetWidth(self.frame) * self.translateX) * offset / 100.;
        CGFloat translateY = (CGRectGetWidth(self.frame) * self.translateY) * abs(offset) / 100.;
        CATransform3D t = CATransform3DMakeTranslation(translateX, translateY, 0.);

        view.layer.transform = CATransform3DRotate(t, DEGREES_TO_RADIANS(angle), self.rotationX, self.rotationY, self.rotationZ);
    }
}

- (NSUInteger)currentPage
{
    CGFloat pageWidth = self.frame.size.width;
    float fractionalPage = self.contentOffset.x / pageWidth;
    return lround(fractionalPage);
}

- (void)loadNextPage:(BOOL)animated
{
    [self loadPageIndex:self.currentPage + 1 animated:animated];
}

- (void)loadPreviousPage:(BOOL)animated
{
    [self loadPageIndex:self.currentPage - 1 animated:animated];
}

- (void)loadPageIndex:(NSUInteger)index animated:(BOOL)animated
{
    CGRect frame = self.frame;
    frame.origin.x = frame.size.width * index;
    frame.origin.y = 0;
    
    [self scrollRectToVisible:frame animated:animated];
}

@end

使用详细例子

CardViewController.h
#import <UIKit/UIKit.h>
#import "HJTCardView.h"
@interface CardViewController : UIViewController<UIScrollViewDelegate>
@property (nonatomic,strong)HJTCardView *scrollView;
@end
CardViewController.m
#import "CardViewController.h"
#import "masonry.h"
#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height


@interface CardViewController ()<UIScrollViewDelegate>
{
//上方文字的数组
    NSMutableArray *topArray;
//下方文字的数组
    NSMutableArray *downArray;
//背景图片数组
    NSMutableArray *imgArray;
    NSInteger number;
//卡片
    UIView *view;
//UIScrollView偏移
    NSInteger offset;
}

@end

@implementation CardViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    //关闭ScrollView自动调整 不然会出现视图控制器上方空白的问题
    self.automaticallyAdjustsScrollViewInsets = NO;
   
    self.navigationController.navigationBar.hidden = YES;
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bgone@2x"]];
    self.scrollView = [[HJTCardView alloc]initWithFrame:CGRectMake(0, 0, 200, 400)];
    self.scrollView.center = CGPointMake(kScreenW/2, 300);
    [self.view addSubview:self.scrollView];
    self.scrollView.effect = HJTCardViewEffectCarousel;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    
    
    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeSystem];
    myButton.frame = CGRectMake(0, 0, 80, 40);
    myButton.layer.borderColor = [UIColor cyanColor].CGColor;
    myButton.layer.borderWidth = 2;
    myButton.layer.cornerRadius = 20;
    myButton.clipsToBounds = YES;
    [myButton setTintColor:[UIColor cyanColor]];
    [myButton setBackgroundColor:[UIColor colorWithRed:225/255.0 green:225/255.0 blue:225/255.0 alpha:1]];
    [myButton addTarget:self action:@selector(DoneTask) forControlEvents:UIControlEventTouchDown];
    myButton.center = CGPointMake(kScreenW/2, kScreenH-100);
    [myButton setTitle:@"完成任务" forState:UIControlStateNormal];
    [self.view addSubview:myButton];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(15, 20, 20, 20);
    [backButton setBackgroundImage:[UIImage imageNamed:@"task-return@2x"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backPreviousPage) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:backButton];
    
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [shareButton addTarget:self action:@selector(doShare) forControlEvents:UIControlEventTouchDown];
    [shareButton setBackgroundImage:[UIImage imageNamed:@"share-b@2x"] forState:UIControlStateNormal];
    [self.view addSubview:shareButton];
    [shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@20);
        make.height.equalTo(@20);
        make.centerY.equalTo(backButton.mas_centerY);
        make.left.equalTo(backButton.mas_right).offset(20);
    }];
    
    topArray = [NSMutableArray arrayWithObjects:@"123rwefwefwerwefwefwfwe",@"456rwerwefwwfwefwrewrwerwe",@"erwerwerewtwegwwegwe789", nil];
    downArray = [NSMutableArray arrayWithObjects:@"sajfqgiu2331wfgiqwubfijwbifuqbwiufbiqwfqwfrtertewwgewgwegwtgewgwegwegwerwewetwetweytwwefwewfeyyewyeryewrfqwrqwfdwqfwfwrfwerwerwerwerwrqwfqw",@"sajfqgiuwfgiqwubf4421ijwbifuqbwiufbiqwfqwfqwfqw",@"s555ajfqgiuwfgiqwubfijwbifuqbwiufbiqwfqwfqwfqw", nil];
    imgArray = [NSMutableArray arrayWithObjects:@"green@2x",@"yellow@2x",@"purple@2x", nil];
    for (int i = 0; i < 3; i ++) {
        [self createCardWithColorAndtopTitle:topArray downTitle:downArray count:i imgs:imgArray];
    }
    
    
    
    
}


-(void)backPreviousPage
{
    [self.navigationController popViewControllerAnimated:NO];
}

-(void)doShare
{
    
}
//封装上下内容 以及背景图的设置方法
- (void)createCardWithColorAndtopTitle:(NSMutableArray *)TopArray downTitle:(NSMutableArray *)DownArray count:(NSInteger)count imgs:(NSMutableArray *)Imgs
{
    CGFloat width = CGRectGetWidth(self.scrollView.frame);
    CGFloat height = CGRectGetHeight(self.scrollView.frame);
    
    CGFloat x = self.scrollView.subviews.count * width;
    
    view = [[UIView alloc] initWithFrame:CGRectMake(x, 0, 240, 288)];
    view.layer.cornerRadius = 8.;
    UIImageView *pinkyView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 29, 22, 22)];
    pinkyView.image = [UIImage imageNamed:@"done@2x"];
    view.tag = count+200;
    [view addSubview:pinkyView];
    
    UILabel *topLabel = [[UILabel alloc]init];
    topLabel.numberOfLines = 0;
    topLabel.textColor = [UIColor whiteColor];
    [view addSubview:topLabel];
    [topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(pinkyView.mas_right).offset(10);
        make.centerY.equalTo(pinkyView.mas_centerY);
        make.width.equalTo(@(180));
        make.height.equalTo(@(50));
    }];
    
    UILabel *downLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 220, 205)];
    downLabel.center = CGPointMake(view.frame.size.width/2, 173);
    downLabel.numberOfLines = 0;
    downLabel.textColor = [UIColor lightGrayColor];
    [view addSubview:downLabel];
    
    
    view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:Imgs[count]]];
    topLabel.text = TopArray[count];
    downLabel.text =DownArray[count];
    
    [self.scrollView addSubview:view];
    self.scrollView.contentSize = CGSizeMake(x + width, height);
//     offset =  (NSInteger)(self.scrollView.contentOffset.x / [UIScreen mainScreen].bounds.size.width);
    
}
#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    // 计算当前在第几页
    offset =  (NSInteger)(self.scrollView.contentOffset.x / 200);
   
}

-(void)DoneTask
{
    //通过UIScrollViewDelegate协议找到对应的View
    if (offset==0) {
        UIView *myView = [self.view viewWithTag:200];
        myView.backgroundColor = [UIColor redColor];
    }
    else if (offset==1)
    {
        UIView *myView = [self.view viewWithTag:201];
        myView.backgroundColor = [UIColor blueColor];
    }
    else if (offset==2)
    {
        UIView *myView = [self.view viewWithTag:202];
        myView.backgroundColor = [UIColor cyanColor];
    }
   
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,132评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,802评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,566评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,858评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,867评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,695评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,064评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,705评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,915评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,677评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,796评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,432评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,041评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,992评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,223评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,185评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,535评论 2 343

推荐阅读更多精彩内容