【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
这是一个大工程,请从工程中寻找相关模块代码.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 177,252评论 25 709
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,828评论 4 61
  • 需要在全局设置里设置一个虚拟网卡然后在单个机器中把网络设置为host-only
    你说你要一场阅读 4,751评论 0 0
  • 最近天气有点冷,每天早上都不想起来,闹钟一响就醒来了,关了闹钟后睁着眼睛在床上躺了十分钟,终于忍痛起来了。 一起来...
    忧蓝lan阅读 3,085评论 2 3
  • 故障: 油表去年就不准,油量一半油表会显示上线,如油量小半会变成下线提示没油,出现故障关闭从新打开会到标准, 诊断...
    宏宇_8a57阅读 6,563评论 0 1

友情链接更多精彩内容