实现效果
- 实现原理:动画改变文本的y坐标,同时使用把移出父布局的视图立即移到父视图的下方,使用一个临时UIView来交替上下两个视图,达到利用的效果
- 实现核心代码如下:
Object-c版本:
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
typedef void(^OnClickListener)(NSString* title);
@interface ScrollLabel : UILabel
@property(nonatomic,strong) UIView* parentView;
@property(nonatomic,strong) UIButton* upLabel;
@property(nonatomic,strong) UIButton* bottomLabel;
@property(nonatomic,copy) OnClickListener listener;
-(void) setTargetView:(UIView*) parentView withTitleArray:(NSMutableArray*)array;
-(void) setOnClickListener:(OnClickListener)listener;
-(void) start;
-(void) stop;
@end
NS_ASSUME_NONNULL_END
.m文件:
#import "ScrollLabel.h"
#import "UIView+Resize.h"
@interface ScrollLabel()
@property(nonatomic,strong)NSMutableArray* titleArray;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,assign)NSInteger index;
@end
@implementation ScrollLabel
-(instancetype) init{
if (self = [super init]) {
}
return self;
}
-(void) setTargetView:(UIView*) parentView withTitleArray:(NSMutableArray*)array{
if (!parentView || !array || array.count == 0) {
return;
}
self.titleArray = array;
self.parentView = parentView;
self.index = 0;
self.upLabel = [[UIButton alloc] init];
self.upLabel.backgroundColor = [UIColor greenColor];
self.upLabel.tag = 21;
[self.upLabel addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
[self.upLabel setTitle:[array objectAtIndex:self.index] forState:UIControlStateNormal];
self.upLabel.frame = CGRectMake(0, 0, parentView.frame.size.width,parentView.frame.size.height);
self.index ++;
self.bottomLabel = [[UIButton alloc] init];
self.bottomLabel.tag = 22;
[self.bottomLabel addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
self.bottomLabel.frame = CGRectMake(0, self.upLabel.frame.size.height, parentView.frame.size.width,parentView.frame.size.height);
[self.bottomLabel setTitle:[array objectAtIndex:self.index] forState:UIControlStateNormal];
self.bottomLabel.backgroundColor = [UIColor brownColor];
[self.parentView addSubview:self.upLabel];
[self.parentView addSubview:self.bottomLabel];
}
-(void) onClick:(UIButton*) button{
switch (button.tag) {
case 21:
case 22:
if (self.listener) {
self.listener(button.titleLabel.text);
}
break;
default:
break;
}
}
-(void) setOnClickListener:(OnClickListener)list