使用兩個Label(也可以為view网棍,可以在view上添加圖片等,原理一樣)實現(xiàn)垂直方向的廣告輪播
廣告對于一個App來說是必不可少的,隨之而來的就是各種各樣的廣告展現(xiàn)方式仲义,最常見的就是banner,圖片輪播了剑勾,常用的第三方框架SDCycleScrollView埃撵。
? 今天給大家實現(xiàn)一下垂直輪播的廣告(因為公司需要,所以寫了下虽另,小白一枚不足的地方盡情指出來:smile:);原理如下圖:
38759134-F6DE-4BC3-A04D-A4285AE6C079.png
兩個label初始位置為1和2暂刘,當(dāng)1和2滾動到3的位置時,重新定位到2的初始位置捂刺。如此一來就實現(xiàn)了無限滾動谣拣。
效果圖:
1.gif
verticalScroll.h中代碼如下:
#import <UIKit/UIKit.h>
@interface verticalScrollView : UIView
//滾動的時間間隔
@property(nonatomic,assign)NSTimeInterval interval;
//數(shù)據(jù)源
@property(nonatomic,strong)NSArray *dataArray;
@end
.m中代碼:
#import "verticalScrollView.h"
@interface verticalScrollView(){
//定時器募寨,讓label動起來
NSTimer *timer;
//第一個label
UILabel *firstLabel;
//第二個label
UILabel *secondLabel;
}
@end
@implementation verticalScrollView
-(instancetype)initWithFrame:(CGRect)frame{
self=[super initWithFrame:frame];
if (self) {
CGFloat width=frame.size.width;
CGFloat height=frame.size.height;
self.backgroundColor=[UIColor redColor];
firstLabel=[[UILabel alloc] initWithFrame:self.bounds];
secondLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, height, width, height)];
firstLabel.text=self.dataArray[0];
[firstLabel setTextColor:[UIColor blackColor]];
secondLabel.text=self.dataArray[1];
[secondLabel setTextColor:[UIColor blackColor]];
[self addSubview:firstLabel];
[self addSubview:secondLabel];
self.clipsToBounds=YES;
timer=[NSTimer scheduledTimerWithTimeInterval:self.interval target:self selector:@selector(scroll) userInfo:nil repeats:YES];
}
return self;
}
NSInteger I=1;
-(void)scroll{
I++;
i=i>self.dataArray.count-1?0:i;
CGFloat height=firstLabel.frame.size.height;
CGFloat width=firstLabel.frame.size.width;
[UIView animateWithDuration:1 animations:^{
NSArray *labelArray=self.subviews;
//讓label滾動起來
for (UIView *view in labelArray) {
if ([view isKindOfClass:[UILabel class]]) {
UILabel *label=(UILabel *)view;
CGRect rect=label.frame;
rect.origin.y-=height;
label.frame=rect;
}
}
} completion:^(BOOL finished) {
//重新定位label的位置
if (firstLabel.frame.origin.y==-height) {
firstLabel.frame=CGRectMake(0, height,width,height);
firstLabel.text=self.dataArray[I];
}
if (secondLabel.frame.origin.y==-height) {
secondLabel.frame=CGRectMake(0,height, width,height);
secondLabel.text=self.dataArray[I];
}
}];
}
//釋放定時器
-(void)dealloc{
[timer invalidate];
timer=nil;
}
@end
到此滾動廣告已經(jīng)封裝完了,現(xiàn)在可以調(diào)用了森缠。
調(diào)用代碼:
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_aview=[[verticalScrollView alloc] initWithFrame:CGRectMake(100, 100, 200, 40)];
_aview.interval=2.0f;
[self.view addSubview:_aview];
}
@end