【IOS】最簡單方式實現跑馬燈文字效果

實現跑馬等效果,如果想要實現,頭部跟尾部同時出現在一個屏幕中的話,應該使用兩個 Label 比較好實現,于是有了以下思路.

@interface JDMarqueeView ()

@property (nonatomic,copy) NSString *msg; //需要展示的消息
@property (nonatomic,assign) CGFloat textW; //文字長度
@property (nonatomic,retain) UILabel *firstLabel; //跑馬燈的兩個 label
@property (nonatomic,retain) UILabel *secondLabel;

@end
@implementation JDMarqueeView

- (instancetype)initWithFrame:(CGRect)frame andMessage:(NSString *)message
{
    
    self = [super initWithFrame:frame];
    if (self) {
        self.clipsToBounds =YES;
        //為了兩個 label 不至于文字連在一起
        _msg = [NSString stringWithFormat:@"    %@      ",message];
        [self createUI];
    }
    return self;
}

- (void)createUI {
    
    _firstLabel =[JDUtils createLabelWithFrame:CGRectZero Font:14 Text:_msg];
    _firstLabel.textAlignment =NSTextAlignmentLeft;
    [_firstLabel sizeToFit];
    //設置居中
    _firstLabel.centerY =self.sizeHeight/2;
    [self addSubview:_firstLabel];
    
    _textW = _firstLabel.sizeWidth;
    
    //如果文字長度大于控件寬度,則開始滾動
    if (_textW>self.sizeWidth) {
        
        _secondLabel =[JDUtils createLabelWithFrame:_firstLabel.frame Font:14 Text:_msg];
        _secondLabel.textAlignment =NSTextAlignmentLeft;
        _secondLabel.originX =CGRectGetMaxX(_firstLabel.frame);
        [_secondLabel sizeToFit];
        [self addSubview:_secondLabel];
        [self startAnimation];
    }
    
}
- (void)startAnimation
{
    //計算走完一次需要的時間
    NSInteger time = _msg.length / num;
    
    [UIView animateWithDuration:time delay:0 options:UIViewAnimationOptionCurveLinear|UIViewAnimationOptionRepeat animations:^{
        
        _firstLabel.originX =-_textW;
        _secondLabel.originX = 0;
        
    } completion:nil];
}
@end

雖然這個跑馬燈實現簡單,但是有幾點缺點
1.文字滾動初始位置必須是從View左側開始.
2.文字無法暫停

Demo地址:https://github.com/yuying2012/WJDStudyLibrary
這是一個大工程,請從工程中尋找相關模塊代碼.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,558評論 25 708
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,257評論 4 61
  • 需要在全局設置里設置一個虛擬網卡然后在單個機器中把網絡設置為host-only
    你說你要一場閱讀 1,117評論 0 0
  • 最近天氣有點冷,每天早上都不想起來,鬧鐘一響就醒來了,關了鬧鐘后睜著眼睛在床上躺了十分鐘,終于忍痛起來了。 一起來...
    憂藍lan閱讀 417評論 2 3
  • 故障: 油表去年就不準,油量一半油表會顯示上線,如油量小半會變成下線提示沒油,出現故障關閉從新打開會到標準, 診斷...
    宏宇_8a57閱讀 2,147評論 0 1