// // LXDanMuTrackView.m // LXAnimationTest // // Created by lianxiang on 2018/8/14. // Copyright © 2018年 com.giga.ios. All rights reserved. // #import "LXDanMuTrackView.h" @implementation LXDanMuTrackView - (instancetype)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { [self dataConfig]; } return self; } -(void)dataConfig{ _showingArray = [[NSMutableArray alloc] init]; _waitShowArray = [[NSMutableArray alloc] init]; } - (void)appendWithCustomView:(UIView *)view{ view.frame = CGRectMake(self.frame.size.width,view.frame.origin.y, view.frame.size.width,view.frame.size.height); view.center = CGPointMake(view.center.x, TRACK_HEIGHT/2); if (_showingArray.count) { UIView *lastView = [_showingArray lastObject]; //最右侧的那条弹幕还没有完全出现在屏幕中 if (CGRectGetMaxX(lastView.frame) + TRACK_HORIZONTAL_PADDING > self.frame.size.width || _waitShowArray.count) { //把这条弹幕加到等待数组中 [_waitShowArray addObject:view]; }else{ //加入轨道 [self addSubview:view]; //加入展示数组 [_showingArray addObject:view]; } }else{ [self addSubview:view]; [_showingArray addObject:view]; } } - (void)moveViewWithSpeed:(float)speed{ //正在展示的弹幕自减一次 for (UIView *view in _showingArray) { view.frame = CGRectMake(view.frame.origin.x - speed, view.frame.origin.y, view.frame.size.width, view.frame.size.height); } //正在展示的弹幕 if (_showingArray.count){ UIView *firstView = [_showingArray firstObject]; UIView *lastView = [_showingArray lastObject]; if (CGRectGetMaxX(firstView.frame) < 0) { //已移除屏幕 remove [firstView removeFromSuperview]; [_showingArray removeObjectAtIndex:0]; } if (_waitShowArray.count) { //最右侧的view 已经完全出现 if (CGRectGetMaxX(lastView.frame) + TRACK_HORIZONTAL_PADDING <= self.frame.size.width) { //转移数组 [_showingArray addObject:[_waitShowArray firstObject]]; [_waitShowArray removeObjectAtIndex:0]; [self addSubview:[_showingArray lastObject]]; } } } } - (float)rightOutScreenWidth { float outScreenWidth = 0.0; //如果等待数组中有值 if (_waitShowArray.count) { //先遍历所有等待数组中的view,累加长度和间距 for (UIView *view in _waitShowArray) { outScreenWidth += view.frame.size.width + TRACK_HORIZONTAL_PADDING; } } //如果展示数组中有值 if (_showingArray.count) { //拿出最右侧的view UIView *lastView = [_showingArray lastObject]; //算出出屏宽 float rightOutWidth = CGRectGetMaxX(lastView.frame) - self.frame.size.width; if (rightOutWidth < 0) { rightOutWidth = 0; } outScreenWidth += rightOutWidth; } return outScreenWidth; } //清理轨道 - (void)cleanTrack { for (UIView *view in _showingArray) { [view removeFromSuperview]; } [_showingArray removeAllObjects]; [_waitShowArray removeAllObjects]; } @end