iOS 跑馬燈的實(shí)現(xiàn)

介紹

我們一說(shuō)起跑馬燈第一個(gè)想到的就是:山寨機(jī)。接下來(lái)介紹的跑馬燈和那個(gè)跑馬燈是不一樣滴。在iOS中,跑馬燈是指label上的字自動(dòng)滾動(dòng),形成類(lèi)似跑馬燈似的條幅。像這樣子:

autoRunLabel.gif

接下來(lái)就簡(jiǎn)單看看這效果是怎么實(shí)現(xiàn)的。

實(shí)現(xiàn)

1、
首先我們從這個(gè)圖片里面能聯(lián)想到如果實(shí)現(xiàn)這個(gè)效果必然需要使用到動(dòng)畫(huà),或者還有有用scrollView的思路,這里我是用的動(dòng)畫(huà)的方式實(shí)現(xiàn)的。
2、.h文件
自定義一個(gè)繼承UIViewLGJAutoRunLabel類(lèi),在.h文件中:

@class LGJAutoRunLabel;

typedef NS_ENUM(NSInteger, RunDirectionType) {
    LeftType = 0,
    RightType = 1,
};

@protocol LGJAutoRunLabelDelegate <NSObject>

@optional
- (void)operateLabel: (LGJAutoRunLabel *)autoLabel animationDidStopFinished: (BOOL)finished;

@end

@interface LGJAutoRunLabel : UIView

@property (nonatomic, weak) id <LGJAutoRunLabelDelegate> delegate;
@property (nonatomic, assign) CGFloat speed;
@property (nonatomic, assign) RunDirectionType directionType;

- (void)addContentView: (UIView *)view;
- (void)startAnimation;
- (void)stopAnimation;

定義一個(gè)NS_ENUM用來(lái)判斷自動(dòng)滾動(dòng)的方向,分別是左和右,聲明一個(gè)可選類(lèi)型的協(xié)議,用來(lái)在controller中調(diào)用并對(duì)autoLabel進(jìn)行操作。聲明對(duì)外的屬性和方法。這里一目了然,主要的實(shí)現(xiàn)思路都集中在.m文件中。
3、.m文件
聲明“私有”變量和屬性:

@interface LGJAutoRunLabel()<CAAnimationDelegate>
{
    CGFloat _width;
    CGFloat _height;
    CGFloat _animationViewWidth;
    CGFloat _animationViewHeight;
    BOOL _stoped;
    UIView *_contentView;//滾動(dòng)內(nèi)容視圖
}
@property (nonatomic, strong) UIView *animationView;//放置滾動(dòng)內(nèi)容視圖
@end

初始化方法:

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self == [super initWithFrame:frame]) {
        _width = frame.size.width;
        _height = frame.size.height;
        
        self.speed = 1.0f;
        self.directionType = LeftType;
        self.layer.masksToBounds = YES;
        self.animationView = [[UIView alloc] initWithFrame:CGRectMake(_width, 0, _width, _height)];
        [self addSubview:self.animationView];
    }
    return self;
}

將滾動(dòng)內(nèi)容視圖contentView添加到動(dòng)畫(huà)視圖animationView上:

- (void)addContentView:(UIView *)view {
    
    [_contentView removeFromSuperview];
    view.frame = view.bounds;
    _contentView = view;
    self.animationView.frame = view.bounds;
    [self.animationView addSubview:_contentView];
    
    _animationViewWidth = self.animationView.frame.size.width;
    _animationViewHeight = self.animationView.frame.size.height;
}

animationView上的contentView自動(dòng)滾動(dòng)起來(lái)的主要方法在這兒,重點(diǎn)來(lái)了,就是這個(gè)- (void)startAnimation方法,看一下這個(gè)方法里面是怎么樣實(shí)現(xiàn)的:

- (void)startAnimation {
    [self.animationView.layer removeAnimationForKey:@"animationViewPosition"];
    _stoped = NO;
    
    CGPoint pointRightCenter = CGPointMake(_width + _animationViewWidth / 2.f, _animationViewHeight / 2.f);
    CGPoint pointLeftCenter  = CGPointMake(-_animationViewWidth / 2, _animationViewHeight / 2.f);
    CGPoint fromPoint        = self.directionType == LeftType ? pointRightCenter : pointLeftCenter;
    CGPoint toPoint          = self.directionType == LeftType ? pointLeftCenter  : pointRightCenter;
    
    self.animationView.center = fromPoint;
    UIBezierPath *movePath    = [UIBezierPath bezierPath];
    [movePath moveToPoint:fromPoint];
    [movePath addLineToPoint:toPoint];
    
    CAKeyframeAnimation *moveAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    moveAnimation.path                 = movePath.CGPath;
    moveAnimation.removedOnCompletion  = YES;
    moveAnimation.duration             = _animationViewWidth / 30.f * (1 / self.speed);
    moveAnimation.delegate             = self;
    [self.animationView.layer addAnimation:moveAnimation forKey:@"animationViewPosition"];
}

↘?首先先把animationView.layer上的動(dòng)畫(huà)移除掉,接下來(lái)就是要找到animationView\contentViewpointCenter這里把這個(gè)中點(diǎn)當(dāng)做是animationView或者是contentView都行,因?yàn)檫@兩個(gè)視圖的frame是相等的,這步找左右中點(diǎn)的意義在于,完全顯示出文字內(nèi)容,因?yàn)榭赡軙?huì)遇到那種比如文字太長(zhǎng)了,view長(zhǎng)度不夠,不能完全顯示出來(lái)文字的全部?jī)?nèi)容, 這里我們找到中點(diǎn),也就相當(dāng)于確定了內(nèi)容視圖要滑動(dòng)的范圍了,接下來(lái)根據(jù)起始方向的枚舉值設(shè)置fromPointtoPoint這里我們默認(rèn)是從右向左滾動(dòng)的。這里我們做動(dòng)畫(huà)設(shè)置,用到了貝塞爾曲線,我們?cè)O(shè)置UIBezierPath的起始位置就是fromPoint也就是屏幕右方(我們看不見(jiàn))self.animationView.center。終止位置是屏幕左方toPoint此時(shí)animationView滾動(dòng)的起始位置的首和終止位置的尾的距離正好是屏幕的寬度。這里我們使用CAKeyframeAnimation關(guān)鍵幀動(dòng)畫(huà),moveAnimation.path = movePath.CGPath;,moveAnimation.removedOnCompletion = YES;動(dòng)畫(huà)完成后就將動(dòng)畫(huà)移除,不保留最終的狀態(tài)。[self.animationView.layer addAnimation:moveAnimation forKey:@"animationViewPosition"];將動(dòng)畫(huà)添加到animationView.layer上。

(這段是對(duì)上面代碼的解釋?zhuān)?br> -------------------分割線-------------------

接下來(lái)的這個(gè)就是代理方法的實(shí)現(xiàn)了,當(dāng)動(dòng)畫(huà)完成后悔調(diào)用LGJAutoRunLabelDelegate我們自定義的delegate方法。

- (void)stopAnimation {
    _stoped = YES;
    [self.animationView.layer removeAnimationForKey:@"animationViewPosition"];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if (self.delegate && [self.delegate respondsToSelector:@selector(operateLabel:animationDidStopFinished:)]) {
        [self.delegate operateLabel:self animationDidStopFinished:flag];
    }
    if (flag && !_stoped) {
        [self startAnimation];
    }
}

4、在controller中使用方法
主要的方法就是聲明LGJAutoRunLabel實(shí)例,將代理設(shè)為自身,聲明directionType默認(rèn)為Left,在runLabel上創(chuàng)建label也就是我們看到的文字。其余方法一目了然了。

//MARK:- CreateAutoRunLabel
- (void)createAutoRunLabel {
    LGJAutoRunLabel *runLabel = [[LGJAutoRunLabel alloc] initWithFrame:CGRectMake(0, 100, kWidth, 50)];
    runLabel.delegate = self;
    runLabel.directionType = LeftType;
    [self.view addSubview:runLabel];
    [runLabel addContentView:[self createLabelWithText:@"繁華聲 遁入空門(mén) 折煞了夢(mèng)偏冷 輾轉(zhuǎn)一生 情債又幾 如你默認(rèn) 生死枯等 枯等一圈 又一圈的 浮圖塔 斷了幾層 斷了誰(shuí)的痛直奔 一盞殘燈 傾塌的山門(mén) 容我再等 歷史轉(zhuǎn)身 等酒香醇 等你彈 一曲古箏" textColor:[self                                                                                                                                                              randomColor] labelFont:[UIFont systemFontOfSize:14]]];
    [runLabel startAnimation];
}

- (UILabel *)createLabelWithText: (NSString *)text textColor:(UIColor *)textColor labelFont:(UIFont *)font {
    NSString *string = [NSString stringWithFormat:@"%@", text];
    CGFloat width = [UILabel getWidthByTitle:string font:font];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 50)];
    label.font = font;
    label.text = string;
    label.textColor = textColor;
    return label;
}

- (UIColor *)randomColor {
    return [UIColor colorWithRed:[self randomValue] green:[self randomValue] blue:[self randomValue] alpha:1];
}

- (CGFloat)randomValue {
    return arc4random()%255 / 255.0f;
}

總結(jié)

這個(gè)例子挺小的,主要思路就是利用動(dòng)畫(huà)將其變活,可能不太好理解的地方就是在動(dòng)畫(huà)移動(dòng)的path這個(gè)路徑的距離上,我們想這個(gè)路徑的時(shí)候肯定要這樣想,我讓動(dòng)畫(huà)從最初我看不見(jiàn)的地方出現(xiàn),然后最后到我看不見(jiàn)的地方消失,這個(gè)中間的距離之差就是屏幕的寬度了,而這個(gè)屏幕的寬度正好我們可以用contentView.frame來(lái)表示。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容