跑马灯

很多项目中在新闻页要求跑马灯的效果,特记下来,方便下次使用

//创建label

UILabel *lable = [[UILabel alloc]init];

lable.font = [UIFont systemFontOfSize:15];

//设置label显示文字

NSString *textString =@"测试数据测试数据测试数据测试数据测试数据测试数据测试数据测试数据测试数据";

lable.text = textString;

lable.backgroundColor = [UIColor yellowColor];

//获取文字的长度,方便做长度适配

CGSize textSize =[lable.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}];

lable.frame = CGRectMake(self.view.bounds.size.width,0, [lable.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}].width,40);

UIView *subView = [[UIView alloc]initWithFrame:CGRectMake(100,50,self.view.bounds.size.width -100,40)];

subView.backgroundColor = [UIColor redColor];

[self.view addSubview:subView];

[subView addSubview:lable];

subView.clipsToBounds =YES;

CGFloat speet;

//判断文字长度是否大于label显示的长度,以此来设置文字显示的时长

if(textSize.width >self.view.bounds.size.width -100) {

speet = textSize.width/15;

}else{

speet = (self.view.bounds.size.width -100)/15;

}

lable.layer.anchorPoint = CGPointMake(0,0);

//设置动画

CABasicAnimation *action1 = [CABasicAnimation animation];

action1.keyPath =@"position";

action1.fromValue = [NSValue valueWithCGPoint:CGPointMake(textSize.width,0)];

action1.toValue = [NSValue valueWithCGPoint:CGPointMake(-textSize.width,0)];

action1.repeatCount =1e100f;

//设置文字显示时长

action1.duration =0.5*speet;

action1.removedOnCompletion =NO;

action1.fillMode = kCAFillModeBoth;

//添加动画

[lable.layer addAnimation:action1 forKey:nil];

你可能感兴趣的:(跑马灯)