iOS滚动label广告效果的简单实现

有时候公司会有这样的需求,上下滚动的广告位

用一个简单的方法来实现,用两个label(或者是两个View 具体随便)上下滚动,运用计时器和UIView动画实现

具体代码如下,封装到了一个view中

.h中传入值

#import <UIKit/UIKit.h>

@interface GDUDTurnView : UIView
@property (nonatomic,strong) NSArray *turnArray;
@end
#import "GDUDTurnView.h"
@interface GDUDTurnView ()
{
    UILabel *label1;
    UILabel *label2;
    NSTimer *timer;
    BOOL wichOne;
    int count;
}
@end
@implementation GDUDTurnView

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.clipsToBounds = YES;
        
    }
    return self;
}

- (void)timer{
    count++;
    if (count>_turnArray.count-1) {
        count = 0;
    }
    [UIView animateWithDuration:0.3 animations:^{
        if (!wichOne) {
            label1.frame = CGRectMake(0, -self.frame.size.height, self.frame.size.width, self.frame.size.height);
            label2.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        }
        if (wichOne) {
            label1.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
            label2.frame = CGRectMake(0, -self.frame.size.height, self.frame.size.width, self.frame.size.height);
        }
    } completion:^(BOOL finished) {
        wichOne = !wichOne;
        if ((int)label1.frame.origin.y==-self.frame.size.height) {
            label1.frame = CGRectMake(0, self.frame.size.height, self.frame.size.width, self.frame.size.height);
            label1.text = _turnArray[count];
        }
        if ((int)label2.frame.origin.y==-self.frame.size.height) {
            label2.frame = CGRectMake(0, self.frame.size.height, self.frame.size.width, self.frame.size.height);
            label2.text = _turnArray[count];
        }
    }];
    
}

- (void)setTurnArray:(NSArray *)turnArray {
    _turnArray = turnArray;
    count = 1;
    if (_turnArray.count == 0) {
        return;
    }
    if (_turnArray.count == 1) {
        label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        label1.text = _turnArray[0];
        label1.backgroundColor = [UIColor redColor];
        [self addSubview:label1];
    }else{
        label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        label1.text = _turnArray[0];
        label1.backgroundColor = [UIColor redColor];
        [self addSubview:label1];
        
        label2 = [[UILabel alloc] initWithFrame:CGRectMake(0, self.frame.size.height, self.frame.size.width, self.frame.size.height)];
        label2.text = _turnArray[1];
        label2.backgroundColor = [UIColor blueColor];
        [self addSubview:label2];
        
        timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timer)
                                               userInfo:@"aaaa" repeats:YES];
    }
}

简单思路就是这样的,具体的约束条件可以自己添加

posted @ 2017-02-24 09:52  NSJELLY  阅读(5433)  评论(0编辑  收藏  举报