• iOS 商品倒计时 限时特价 限时优惠 功能的封装


    最近项目中多个页面用到了 商品特价倒计时的功能  为了偷懒 于是自己封装了一个限时抢购 倒计时的view 代码实现如下:

    定向价 限时特价 模型代码实现:

    #pragma mark 商品定向价模型
    @interface STGoodsOrientationPrice : STBaseModel
    
    /**定向价**/
    @property (nonatomic, copy) NSString *price;
    
    /**定向价开始时间**/
    @property (nonatomic, copy) NSString *started_at;
    
    /***定向价结束时间*/
    @property (nonatomic, copy) NSString *expired_at;
    
    /**商品分润**/
    @property (nonatomic, copy) NSString *rebate;
    
    /***  特价提前曝光中需要的字段 推荐价*/
    @property (nonatomic,copy)NSString *  promotion_price;
    
    /** *特价提前曝光中需要的字段 原价*/
    @property (nonatomic,copy)NSString *  origin_price;
    
    /***  特价提前曝光需要的背景图片字段*/
    @property (nonatomic,copy)NSString * image;
    
    /***自定义属性 判断活动是否已经结束 在sku里面会用到*/
    @property (nonatomic,assign,getter=isActivityEnd)BOOL activityEnd;
    
    @end

    @implementation STGoodsOrientationPrice

    @end

     

    限时特价 view实现代码

    #import <UIKit/UIKit.h>
    /**
     *  定向价格的view
    */
    
    //定义活动进行中的回调
    typedef void (^orientationPriceViewStartBlock)();
    
    //定义活动结束的回调
    typedef void (^orientationPriceViewEndBlock)();
    
    @class STGoodsOrientationPrice; //定向价模型
    
    @interface STOrientationPriceView : UIView
    
    /**定向价模型**/
    @property(nonatomic,strong)STGoodsOrientationPrice *orientation;
    
    /**活动进行中的回调**/
    @property(nonatomic,strong)orientationPriceViewStartBlock orientationPriceViewStart;
    
    /**活动结束的回调**/
    @property(nonatomic,strong)orientationPriceViewEndBlock orientationPriceViewEndBlock;
    
    /***创建定时器*/
    @property(nonatomic,strong)NSTimer *timer;
    
    /***创建定时器*/
    @property(nonatomic,strong)NSTimer *timer1;
    
    
    /***是否需要右侧展示原价view*/
    @property(nonatomic,assign)BOOL showOldPrice;
    
    
    /**重新开启定时器**/
    - (void)startTimer;
    
    @end
    #import "STOrientationPriceView.h"
    #import "STGoodsOrientationPrice.h"
    #import "NSDate+SY.h"
    #define orientationItemW 18
    
    @interface STOrientationPriceView()
    
    /***  底色图*/
    @property(nonatomic,strong)UIImageView *bgImageView;
    
    /***  限时优惠label*/
    @property(nonatomic,strong)UIButton *saleButton ;
    
    /* *  价格的图 */
    @property(nonatomic,strong)UIImageView *moneyLabel;
    
    /** *  价格的label*/
    @property(nonatomic,strong)UILabel *priceLabel;
    
    /** *  原价label*/
    @property(nonatomic,strong)UILabel *oldPriceLabel;
    
    /** *  右侧时间提示label*/
    @property(nonatomic,strong) UILabel*rightLabel;
    
    /***  右侧时间提示label上面正式开始的label*/
    @property(nonatomic,strong) UILabel*startLabel;
    
    /***活动结束的label*/
    @property(nonatomic,strong) UILabel*endLabel;
    
    /*** 小时*/
    @property(nonatomic,strong)UIButton *hourLabel;
    
    /*** 点 左 */
    @property(nonatomic,strong)UIImageView *pointLeft;
    
    /*** 分钟*/
    @property(nonatomic,strong)UIButton *minuteLabel;
    
    /*** 点 右 */
    @property(nonatomic,strong)UIImageView *pointRight;
    
    /*** 秒*/
    @property(nonatomic,strong)UIButton *secondLabel;
    
    
    @end
    
    @implementation STOrientationPriceView
    
    #pragma mark lazy
    - (NSTimer *)timer
    {
        if (!_timer) {
            _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(modifyDate) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
        }
        return _timer;
    }
    
    
    #pragma mark lazy
    - (NSTimer *)timer1
    {
        if (!_timer1) {
            _timer1 = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(modifEndDate) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:_timer1 forMode:NSRunLoopCommonModes];
        }
        return _timer1;
    }
    
    #pragma mark /**重新开启定时器**/
    - (void)startTimer
    {
        [self setOrientation:_orientation];
    }
    
    
    - (instancetype)initWithFrame:(CGRect)frame
    {
        if (self = [super initWithFrame:frame]) {
            [self setUpView];
        }
        
        return self;
    }
    
    
    #pragma mark init
    - (void)awakeFromNib
    {
        [super awakeFromNib];
        
        [self setUpView];
        
    }
    
    - (void)setUpView
    {
        self.userInteractionEnabled = NO;
        
        _bgImageView = [[UIImageView alloc] init];
        [self addSubview:_bgImageView];
        
        _saleButton = [[UIButton alloc] init];
        _saleButton.titleLabel.font  = [UIFont systemFontOfSize:15];
        [_saleButton setTitle:@"限时优惠" forState:UIControlStateNormal];
        [self addSubview:_saleButton];
        
        _moneyLabel = [[UIImageView alloc] init];
        _moneyLabel.image = [UIImage imageNamed:@"goods_orientation_money"];
        [self addSubview:_moneyLabel];
        
        _priceLabel = [[UILabel alloc] init];
        _priceLabel.text = @"0.00";
        _priceLabel.font = [UIFont systemFontOfSize:29];
        _priceLabel.textColor = [UIColor whiteColor];
        [self addSubview:_priceLabel];
        
        
     
        _oldPriceLabel = [[UILabel alloc] init];
        _oldPriceLabel.text = @"0.00";
        _oldPriceLabel.hidden = YES;
        _oldPriceLabel.font = [UIFont systemFontOfSize:14];
        _oldPriceLabel.textColor = [UIColor colorWithHexString:@"fbe47a"];
        [self addSubview:_oldPriceLabel];
        NSString *oldPrice = @"¥ 12345";
        NSUInteger length = [oldPrice length];
        NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:oldPrice];
        [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, length)];
        [attri addAttribute:NSStrikethroughColorAttributeName value:[UIColor colorWithHexString:@"fbe47a"] range:NSMakeRange(0, length)];
        [_oldPriceLabel setAttributedText:attri];
        
        
        
        _rightLabel = [[UILabel alloc] init];
        _rightLabel.font = [UIFont systemFontOfSize:10];
        _rightLabel.textColor = [UIColor colorWithHexString:@"373737"];
        [self addSubview:_rightLabel];
        
        _startLabel = [[UILabel alloc] init];
        _startLabel.font = [UIFont systemFontOfSize:17];
        _startLabel.textColor = [UIColor colorWithHexString:@"373737"];
        [self addSubview:_startLabel];
        
        _endLabel = [[UILabel alloc] init];
        _endLabel.font = [UIFont systemFontOfSize:17];
        _endLabel.textColor = [UIColor colorWithHexString:@"b3b3b3"];
        [self addSubview:_endLabel];
        
        _hourLabel = [[UIButton alloc] init];
        _hourLabel.titleLabel.font  = [UIFont systemFontOfSize:11];
        [_hourLabel setTitle:@"00" forState:UIControlStateNormal];
        [_hourLabel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_hourLabel setBackgroundImage:[UIImage imageNamed:@"goods_orientation_blackRectangle"] forState:UIControlStateNormal];
        [self addSubview:_hourLabel];
        
        _pointLeft = [[UIImageView alloc] init];
        _pointLeft.image = [UIImage imageNamed:@"goods_orientation_point"];
        [self addSubview:_pointLeft];
        
        _minuteLabel = [[UIButton alloc] init];
        _minuteLabel.titleLabel.font =[UIFont systemFontOfSize:11];
        [_minuteLabel setTitle:@"00" forState:UIControlStateNormal];
        [_minuteLabel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_minuteLabel setBackgroundImage:[UIImage imageNamed:@"goods_orientation_blackRectangle"] forState:UIControlStateNormal];
        [self addSubview:_minuteLabel];
        
        _pointRight = [[UIImageView alloc] init];
        _pointRight.image = [UIImage imageNamed:@"goods_orientation_point"];
        [self addSubview:_pointRight];
        
        _secondLabel = [[UIButton alloc] init];
        _secondLabel.titleLabel.font =[UIFont systemFontOfSize:11];
        [_secondLabel setTitle:@"00" forState:UIControlStateNormal];
        [_secondLabel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_secondLabel setBackgroundImage:[UIImage imageNamed:@"goods_orientation_blackRectangle"] forState:UIControlStateNormal];
        [self addSubview:_secondLabel];
        
        
        [self hideTime];
        
        //布局
        [self layout];
    }
    
    #pragma mark layout
    - (void)layout
    {
        
        CGFloat margin = 10;
        
        [_bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(self.mas_width);
            make.height.equalTo(self.mas_height);
            make.left.equalTo(self.mas_left);
            make.top.equalTo(self.mas_top);
        }];
        
        [_saleButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.mas_left).offset(margin);
            make.centerY.equalTo(self.mas_centerY);
            make.width.mas_equalTo(86);
            make.height.mas_equalTo(24);
        }];
        
        [_moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(11);
            make.height.mas_equalTo(15);
            make.left.equalTo(_saleButton.mas_right).offset(margin);
            make.centerY.equalTo(self.mas_centerY);
        }];
        
        CGFloat priceMargin = 3;
        [_priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_moneyLabel.mas_right).offset(priceMargin);
            make.centerY.equalTo(self.mas_centerY);
        }];
        
        
        CGFloat rigthMargin = 16;
        [_rightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.mas_right).offset(-rigthMargin);
            make.top.equalTo(self.mas_top).offset(6);
            
        }];
        
        
        [_startLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.mas_right).offset(-rigthMargin);
            make.top.equalTo(_rightLabel.mas_bottom).offset(5);
        }];
        
        [_endLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.right.equalTo(self.mas_right).offset(-rigthMargin);
            make.centerY.equalTo(self.mas_centerY);
        }];
        
        CGFloat timeW = orientationItemW;
        CGFloat timeMargin =5;
        CGFloat timeTopMargin = 5;
        [_secondLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.mas_right).offset(-16);
            make.top.equalTo(_rightLabel.mas_bottom).offset(timeTopMargin);
            make.width.mas_equalTo(timeW);
        }];
        
        [_pointRight mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(2);
            make.height.mas_equalTo(8);
            make.right.equalTo(_secondLabel.mas_left).offset(-timeMargin);
            make.centerY.equalTo(_secondLabel.mas_centerY);
        }];
        
        
        [_minuteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_pointRight.mas_left).offset(-timeMargin);
            make.top.equalTo(_rightLabel.mas_bottom).offset(timeTopMargin);
            make.width.mas_equalTo(timeW);
        }];
        
        
        [_pointLeft mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(2);
            make.height.mas_equalTo(8);
            make.right.equalTo(_minuteLabel.mas_left).offset(-timeMargin);
            make.centerY.equalTo(_minuteLabel.mas_centerY);
        }];
        
        
        [_hourLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_pointLeft.mas_left).offset(-timeMargin);
            make.top.equalTo(_rightLabel.mas_bottom).offset(timeTopMargin);
            make.width.mas_equalTo(timeW);
        }];
        
        
        [_oldPriceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_hourLabel.mas_left).offset(-12);
            make.centerY.equalTo(self.mas_centerY);
        }];
        
    }
    
    #pragma mark 是否需要展示原价 显示原价 说明是首页的卡片cell
    - (void)setShowOldPrice:(BOOL)showOldPrice
    {
        
        _showOldPrice = showOldPrice;
        
        if (showOldPrice) {
            
            self.priceLabel.font = [UIFont boldSystemFontOfSize:15];
            
            if (IS_IPHONE_4_OR_LESS || IS_IPHONE_5) {
                self.oldPriceLabel.hidden = YES;
            }else{
                self.oldPriceLabel.hidden = NO;
            }
            
            [_saleButton setTitle:@"特价预告" forState:UIControlStateNormal];
            
        }else{
            
            self.oldPriceLabel.hidden = YES;
            [_saleButton setTitle:@"限时优惠" forState:UIControlStateNormal];
    
        }
    }
    
    #pragma mark 设置数据 在这里判断当前定向价展示的状态
    - (void)setOrientation:(STGoodsOrientationPrice *)orientation
    {
        _orientation = orientation;
    
        _priceLabel.text = orientation.price?orientation.price:@"0.00";
        
        _rightLabel.text = orientation.started_at;
        
        //判断活动是否已经结束
        if ([self validEndDate]) {
            
            //活动结束
            [self setupOrientationEnd];
            
            //活动已经结束
            self.orientation.activityEnd = YES;
            
            return;
        }
    
        //判断活动开始时间
        [self validStartate];
      
    }
    
    #pragma mark 判断活动结束时间
    - (BOOL)validEndDate
    {
        // 日期格式化类
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        // 设置日期格式(y:年,M:月,d:日,H:时,m:分,s:秒)
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        
        // 活动结束时间
        NSDate *create = [fmt dateFromString:_orientation.expired_at];
        
        NSTimeZone *zone = [NSTimeZone systemTimeZone]; //获得系统的时区
        
        NSTimeInterval time = [zone secondsFromGMTForDate:create];//以秒为单位返回当前时间与系统格林尼治时间的差
        
        NSDate *createDate =  [create dateByAddingTimeInterval:time];//然后把差的时间加上,就是当前系统准确的时间
        
        // 截止时间data格式
        NSDate *expireDate = [fmt dateFromString:[fmt stringFromDate:createDate]];
        // 当前时间data格式
        NSDate *nowDate = [fmt dateFromString:[fmt stringFromDate:[self getCurrentDate]]];
        // 当前日历
        NSCalendar *calendar = [NSCalendar currentCalendar];
        // 需要对比的时间数据
        NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
        | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
        // 对比时间差
        NSDateComponents *dateCom = [calendar components:unit fromDate:nowDate toDate:expireDate options:0];
        
        if (dateCom.day>1) {
            
            return  NO;
            
        }else{
            
            if (dateCom.month>1) {
                
                return NO;
            
            }else{
               
                if (dateCom.second>0) {
                    return NO;
                }else{
                    
                    if (dateCom.minute>0) {
                        
                        return NO;
                   
                    }else if (dateCom.second>0){
                        
                        return NO;
                    }
                    
                    return YES;
                }
    
                
            }
            
        }
    
        return NO;
    
    }
    
    
    
    
    
    #pragma mark 判断活动开始时间差距
    - (void)validStartate
    {
        // 日期格式化类
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        
        // 活动开始时间
        NSDate *create = [fmt dateFromString:_orientation.started_at];
        
        NSTimeZone *zone = [NSTimeZone systemTimeZone]; //获得系统的时区
        
        NSTimeInterval time = [zone secondsFromGMTForDate:create];//以秒为单位返回当前时间与系统格林尼治时间的差
        
        NSDate *createDate =  [create dateByAddingTimeInterval:time];//然后把差的时间加上,就是当前系统准确的时间
        
        
        //获取当前时间
        NSDate *nowDate = [fmt dateFromString:[fmt stringFromDate:[self getCurrentDate]]];
        
        // 当前日历
        NSCalendar *calendar = [NSCalendar currentCalendar];
    
        if (createDate.isThisYear) { // 今年
            
            
            // 需要对比的时间数据
            NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
            | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
            // 对比时间差
            NSDateComponents *dateCom = [calendar components:unit fromDate:nowDate toDate:createDate options:0];
            
            
            if (dateCom.day>0) {
                
                [self setupOrientation12Out];
    
            }else{
                
                if (dateCom.month>0) {
                    
                    [self setupOrientation12Out];
    
                }else{
                    
            
                    
                    if (dateCom.hour>12) { //12小时之外
                        
                        [self setupOrientation12Out];
                        
                    }else if (dateCom.hour<=12 && dateCom.hour>0){ //12小时之内
                        
                        if (dateCom.hour==12) {
                            
                            if (dateCom.second>0) {
                                [self setupOrientation12Out];
    
                            }else{
                            
                                if (dateCom.minute>0) {
                                    [self setupOrientation12Out];
                                }else{
                                  
                                    [self setupOrientation12In];
                                }
                            }
                            
                        }else{
                            
                            [self setupOrientation12In];
    
                            
                        }
                        
                        
                    }else{ //小于0 表示活动已经开始
                        
                        if (dateCom.minute<=0 && dateCom.second<=0) {
                            
                            [self setupActiveStart];
                            
                        }else{
                            [self setupOrientation12In];
                        }
                        
                    }
    
                    
                    
                }
                
            }
        
        }else{
            
            [self setupOrientation12Out];
            
        }
        
        
    }
    
    
    #pragma mark 设置活动开始信息
    - (void)setupActiveStart
    {
        //设置不能添加到购物车
        weakifySelf
        if(self.orientationPriceViewStart){
            weakSelf.orientationPriceViewStart();
        }
        [self setupOrientationStart];
    }
    
    
    
    - (void)dealloc
    {
        [self.timer invalidate];
        self.timer  = nil;
    }
    
    
    #pragma mark 设置12小时内开购的信息
    - (void)setupOrientation12In
    {
        _endLabel.hidden = YES;
    
        
        if (self.showOldPrice) {
            
            _bgImageView.image = [UIImage imageNamed:@"homeRrientationGreenbg"];
            
        }else{
            
            _bgImageView.image = [UIImage imageNamed:@"goods_orientation_greenbg"];
    
        }
        _rightLabel.text = @"距离开始仅剩";
        [_saleButton setTitleColor:[UIColor colorWithHexString:@"76a505"] forState:UIControlStateNormal];
        [_saleButton setBackgroundImage:[UIImage imageNamed:@"goods_orientation_yellowRectang"] forState:UIControlStateNormal];
        
        [self showTime];
        
     
        //开启定时器
        [self.timer fire];
    
    
    }
    
    #pragma mark 获取当前的准确时间
    - (NSDate*)getCurrentDate
    {
        NSDate *date = [NSDate date]; //获得时间对象
        
        NSTimeZone *zone = [NSTimeZone systemTimeZone]; //获得系统的时区
        
        NSTimeInterval time = [zone secondsFromGMTForDate:date];//以秒为单位返回当前时间与系统格林尼治时间的差
        
        return [date dateByAddingTimeInterval:time];//然后把差的时间加上,就是当前系统准确的时间
    }
    
    
    #pragma mark 修改日期 每一秒掉用一次  修改开始时间
    - (void)modifyDate
    {
        
        // 日期格式化类
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        // 设置日期格式(y:年,M:月,d:日,H:时,m:分,s:秒)
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        
        
        // 活动开始时间
        NSDate *create = [fmt dateFromString:_orientation.started_at];
        
        NSTimeZone *zone = [NSTimeZone systemTimeZone]; //获得系统的时区
        
        NSTimeInterval time = [zone secondsFromGMTForDate:create];//以秒为单位返回当前时间与系统格林尼治时间的差
        
        NSDate *createDate =  [create dateByAddingTimeInterval:time];//然后把差的时间加上,就是当前系统准确的时间
        
        //获取当前时间
        NSDate *nowDate = [self getCurrentDate];
        
        //判断开始时间和 当前时间的差值
        NSDateComponents *cmps = [nowDate deltaFrom:createDate];
        
        //设置十分秒 信息
        NSInteger hour = 0;
        NSInteger minute = 0;
        NSInteger second = 0;
        
        if (cmps.hour<=0 || cmps.minute<=0 || cmps.second<=0) {
            
            
            //判断开始时间和 当前时间的差值
            NSDateComponents *cmps = [createDate deltaFrom:nowDate];
            
            
            //设置十分秒 信息
            hour = cmps.hour;
            minute = cmps.minute;
            second = cmps.second;
            
        }else{
            
            
            //设置十分秒 信息
            hour = cmps.hour;
            minute = cmps.minute;
            second = cmps.second;
            
        }
     
        
        
        if (hour==0 && minute==0 && second==0) {
            
                //掉用活动开始
                [self setupOrientationStart];
            
                [self.timer invalidate];
                self.timer = nil;
            
        }
    
        
        NSString *houreT = [NSString stringWithFormat:@"%02zd",hour>0?hour:0];
        NSString *minuteT = [NSString stringWithFormat:@"%02zd",minute>0?minute:0];
        NSString *secondT = [NSString stringWithFormat:@"%02zd",second>0?second:0];
    
        CGFloat houreW = [houreT boundingRectWithSize:CGSizeMake(MAXFLOAT, orientationItemW) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:11]} context:nil].size.width;
        
        if (houreW>=orientationItemW) {
            [_hourLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(houreW+5);
            }];
        }
        
      
        
        [self.hourLabel setTitle:houreT forState:UIControlStateNormal];
        [self.minuteLabel setTitle:minuteT forState:UIControlStateNormal];
        [self.secondLabel setTitle:secondT forState:UIControlStateNormal];
        
    }
    
    
    #pragma mark 修改日期 每一秒掉用一次 修改结束时间
    - (void)modifEndDate
    {
        
        // 日期格式化类
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        // 设置日期格式(y:年,M:月,d:日,H:时,m:分,s:秒)
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        
        
        // 活动开始时间
        NSDate *create = [fmt dateFromString:_orientation.expired_at];
        
        NSTimeZone *zone = [NSTimeZone systemTimeZone]; //获得系统的时区
        
        NSTimeInterval time = [zone secondsFromGMTForDate:create];//以秒为单位返回当前时间与系统格林尼治时间的差
        
        NSDate *createDate =  [create dateByAddingTimeInterval:time];//然后把差的时间加上,就是当前系统准确的时间
        
        //获取当前时间
        NSDate *nowDate = [self getCurrentDate];
        
        //判断开始时间和 当前时间的差值
        NSDateComponents *cmps = [nowDate deltaFrom:createDate];
        
        //设置十分秒 信息
        NSInteger hour = 0;
        NSInteger minute = 0;
        NSInteger second = 0;
        
        if (cmps.hour<=0 || cmps.minute<=0 || cmps.second<=0) {
            
            
            //判断开始时间和 当前时间的差值
            NSDateComponents *cmps = [createDate deltaFrom:nowDate];
            
            
            if (cmps.day>0) {
                
                //设置十分秒 信息
                hour = cmps.hour+(cmps.day*24);
                
            }else{
                //设置十分秒 信息
                hour = cmps.hour;
            }
           
            minute = cmps.minute;
            second = cmps.second;
            
        }else{
            
            
            //设置十分秒 信息
            hour = cmps.hour;
            minute = cmps.minute;
            second = cmps.second;
            
        }
        
        
        
        if (hour==0 && minute==0 && second==0) {
            
            //掉用活动结束
            [self setupOrientationEnd];
            
            [self.timer1 invalidate];
            self.timer1 = nil;
            
        }
        
        
        NSString *houreT = [NSString stringWithFormat:@"%02zd",hour>0?hour:0];
        NSString *minuteT = [NSString stringWithFormat:@"%02zd",minute>0?minute:0];
        NSString *secondT = [NSString stringWithFormat:@"%02zd",second>0?second:0];
        
        CGFloat houreW = [houreT boundingRectWithSize:CGSizeMake(MAXFLOAT, orientationItemW) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:11]} context:nil].size.width;
        
        if (houreW>orientationItemW) {
            [_hourLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(houreW+10);
            }];
        }
        
        [self.hourLabel setTitle:houreT forState:UIControlStateNormal];
        [self.minuteLabel setTitle:minuteT forState:UIControlStateNormal];
        [self.secondLabel setTitle:secondT forState:UIControlStateNormal];
        
    }
    
    
    
    #pragma mark 设置12小时外开购的信息
    - (void)setupOrientation12Out
    {
        if (self.showOldPrice) {
            
            _bgImageView.image = [UIImage imageNamed:@"homeRrientationGreenbg"];
            
        }else{
            
            _bgImageView.image = [UIImage imageNamed:@"goods_orientation_greenbg"];
            
        }
        [_saleButton setTitleColor:[UIColor colorWithHexString:@"76a505"] forState:UIControlStateNormal];
        [_saleButton setBackgroundImage:[UIImage imageNamed:@"goods_orientation_yellowRectang"] forState:UIControlStateNormal];
        
        [self hideTime];
        
        _endLabel.hidden = YES;
        _rightLabel.hidden = NO;
        _rightLabel.text =[self formatterStartTime];
        _startLabel.text = @"正式开始";
      
    }
    
    #pragma mark 格式化开始时间字符串
    - (NSString*)formatterStartTime
    {
        
        // 日期格式化类
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        // 设置日期格式(y:年,M:月,d:日,H:时,m:分,s:秒)
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        
        NSTimeZone* GTMzone = [NSTimeZone timeZoneForSecondsFromGMT:0];
        [fmt setTimeZone:GTMzone];
        
        // 活动开始时间
        NSDate *create = [fmt dateFromString:_orientation.started_at];
        
        if (create.isThisYear) { // 今年
            
            // 日期格式化类
            NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
            // 设置日期格式(y:年,M:月,d:日,H:时,m:分,s:秒)
            fmt.dateFormat = @"MM-dd HH:mm:ss";
            
            NSTimeZone* GTMzone = [NSTimeZone timeZoneForSecondsFromGMT:0];
            [fmt setTimeZone:GTMzone];
            
            return [fmt stringFromDate:create];
            
        }else{
            
            return _orientation.started_at;
        }
    
        
        
    }
    
    
    #pragma mark 设置1活动开始的信息
    - (void)setupOrientationStart
    {
        _endLabel.hidden = YES;
    
        [self showTime];
        
        
        if (self.showOldPrice) {
            
            _bgImageView.image = [UIImage imageNamed:@"homeRrientationRedbg"];
            
        }else{
            
            _bgImageView.image = [UIImage imageNamed:@"goods_orientation_redbg"];
            
        }
        
        [_saleButton setTitleColor:[UIColor colorWithHexString:@"e72646"] forState:UIControlStateNormal];
        [_saleButton setBackgroundImage:[UIImage imageNamed:@"goods_orientation_yellowRectang"] forState:UIControlStateNormal];
        
        _rightLabel.text = @"距离结束仅剩";
        
        //掉用定时器
        [self.timer1 fire];
    }
    
    #pragma mark 设置1活动结束的信息
    - (void)setupOrientationEnd
    {
        
        //设置可以添加到购物车
        weakifySelf
        if(self.orientationPriceViewEndBlock){
            weakSelf.orientationPriceViewEndBlock();
        }
        
        
        _bgImageView.image = [UIImage imageNamed:@"goods_orientation_graybg"];
        [_saleButton setTitleColor:[UIColor colorWithHexString:@"b3b3b3"] forState:UIControlStateNormal];
        [_saleButton setBackgroundImage:[UIImage imageNamed:@"goods_orientation_grayRectang"] forState:UIControlStateNormal];
        _endLabel.text = @"活动已结束";
        
        _rightLabel.hidden = YES;
        _startLabel.hidden = YES;
        
        [self hideTime];
        
        _endLabel.hidden = NO;
     
    }
    
    #pragma mark 显示时间控件
    - (void)showTime
    {
        _rightLabel.hidden = NO;
        _hourLabel.hidden = NO;
        _pointLeft.hidden = NO;
        _pointRight.hidden = NO;
        _minuteLabel.hidden = NO;
        _secondLabel.hidden = NO;
    }
    
    #pragma mark 隐藏时间控件
    - (void)hideTime
    {
        _rightLabel.hidden = YES;
        _hourLabel.hidden = YES;
        _pointLeft.hidden = YES;
        _pointRight.hidden = YES;
        _minuteLabel.hidden = YES;
        _secondLabel.hidden = YES;
    }
    
    @end

    NSDate+SY 分类代码实现如下:

    #import <Foundation/Foundation.h>
    
    @interface NSDate (SY)
    
    /**
     * 获取当前区域的当前时间
     */
    + (NSDate *)getCurrentDate;
    
    
    /**
     * 比较from和self的时间差值
     */
    - (NSDateComponents *)deltaFrom:(NSDate *)from;
    
    /**
     * 是否为今年
     */
    - (BOOL)isThisYear;
    
    /**
     * 是否为今天
     */
    - (BOOL)isToday;
    
    /**
     * 是否为昨天
     */
    - (BOOL)isYesterday;
    
    @end
    #import "NSDate+SY.h"
    
    @implementation NSDate (SY)
    
    /**
     * 获取当前区域的当前时间
     */
    + (NSDate *)getCurrentDate
    {
        NSDate *date = [NSDate date]; //获得时间对象
        
        NSTimeZone *zone = [NSTimeZone systemTimeZone]; //获得系统的时区
        
        NSTimeInterval time = [zone secondsFromGMTForDate:date];//以秒为单位返回当前时间与系统格林尼治时间的差
        
        return [date dateByAddingTimeInterval:time];//然后把差的时间加上,就是当前系统准确的时间
    }
    
    
    
    
    
    - (NSDateComponents *)deltaFrom:(NSDate *)from
    {
        // 日历
        NSCalendar *calendar = [NSCalendar currentCalendar];
        
        // 比较时间
        NSCalendarUnit unit = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
        
        return [calendar components:unit fromDate:from toDate:self options:0];
    }
    
    - (BOOL)isThisYear
    {
        // 日历
        NSCalendar *calendar = [NSCalendar currentCalendar];
        
        NSInteger nowYear = [calendar component:NSCalendarUnitYear fromDate:[NSDate date]];
        NSInteger selfYear = [calendar component:NSCalendarUnitYear fromDate:self];
        
        return nowYear == selfYear;
    }
    
    
    - (BOOL)isToday
    {
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"yyyy-MM-dd";
        
        NSString *nowString = [fmt stringFromDate:[NSDate date]];
        NSString *selfString = [fmt stringFromDate:self];
        
        return [nowString isEqualToString:selfString];
    }
    
    - (BOOL)isYesterday
    {
        // 日期格式化类
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"yyyy-MM-dd";
        
        NSDate *nowDate = [fmt dateFromString:[fmt stringFromDate:[NSDate date]]];
        NSDate *selfDate = [fmt dateFromString:[fmt stringFromDate:self]];
        
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *cmps = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:selfDate toDate:nowDate options:0];
        
        return cmps.year == 0
        && cmps.month == 0
        && cmps.day == 1;
    }
    
    
    @end

    到这里限时特价的一个自定义view就封装好了  我这里集成到项目中的 效果图如下:

  • 相关阅读:
    stm32 IAP + APP ==>双剑合一(转)
    ClassNotFoundException和NoClassDefFoundError的差别
    浏览器对文字的解析
    hive 配置注意事项及初始化hive 元数据
    移植MonkeyRunner的图片对照和获取子图功能的实现-Appium篇
    导出excel——弹出框
    机器学习类似度计算方法选择理论根据
    数据结构
    八.200多万元得到的创业教训--从3款产品学到的3点
    深圳市安卓工控设备有限公司简单介绍
  • 原文地址:https://www.cnblogs.com/syios/p/5866772.html
Copyright © 2020-2023  润新知