在网页开发当中跑马灯是常用到的,用来显示通知等,在游戏开发当中也如此。
首先来看看效果图:

接下来就简单看看这效果是怎么实现的。
实现方法
1、首先我们从这个图片里面能联想到如果实现这个效果必然需要使用到动画,或者还有有用scrollView的思路,这里我是用的动画的方式实现的。
2、.h文件
自定义一个继承UIView的LGJAutoRunLabel类,在.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;
定义一个NS_ENUM用来判断自动滚动的方向,分别是左和右,声明一个可选类型的协议,用来在controller中调用并对autoLabel进行操作。声明对外的属性和方法。这里一目了然,主要的实现思路都集中在.m文件中。
3、.m文件
声明“私有”变量和属性:
@interface LGJAutoRunLabel()<CAAnimationDelegate>
{
CGFloat _width;
CGFloat _height;
CGFloat _animationViewWidth;
CGFloat _animationViewHeight;
BOOL _stoped;
UIView *_contentView;//滚动内容视图
}
@property (nonatomic, strong) UIView *animationView;//放置滚动内容视图
@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;
}
将滚动内容视图contentView添加到动画视图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自动滚动起来的主要方法在这儿,重点来了,就是这个-










