记:闲暇之余自己写的ios文字显示动画文件。
文字将从左到右从上到下逐个显示,显示的速度可自己控制:
.h头文件代码:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface SWStringAnimation : NSObject
@property(nonatomic, strong)NSArray <NSString *>*letterArray; //用来做动画的文字数组
@property(nonatomic, strong)UIFont *letterFont; //文字大小,有默认值,可不设置
@property(nonatomic, assign)NSTimeInterval timeInterval; //文字刷新时间间隔.有默认值
@property(nonatomic, assign)CGFloat startX;//起始X点坐标.有默认值
@property(nonatomic, assign)CGFloat startY;//起始Y点坐标.有默认值
-(void)startAnimotionOneView:(UIView *)view; //view:当前文字动画显示的父控件
@end
NS_ASSUME_NONNULL_END
.m文件->
//
// SWStringAnimation.m
// stringAnimotion
//
// Created by 数据中心ios on 2019/12/5.
// Copyright © 2019 数据中心ios. All rights reserved.
//
#import “SWStringAnimation.h”
#define mainBounds [UIScreen mainScreen].bounds
#define mainBoundsSize mainBounds.size
#define mainBoundsWidth mainBoundsSize.width
#define mainBoundsHeight mainBoundsSize.height
@implementation SWStringAnimation{
NSMutableArray *labelArray;
NSTimer *letterTimer;
UIView *parentsView;
}
-(void)startAnimotionOneView:(UIView *)view{
if(self.letterArray.count<1){
NSLog(@"未设置文字");
return;
}
if(view == nil){
NSLog(@"文字动画父控件不能为nil");
return;
}
parentsView = view;
labelArray = [[NSMutableArray alloc]init];
for(int i=0;i<self.letterArray.count;i++){
UILabel *strLabel = [[UILabel alloc]init];
strLabel.numberOfLines = 0;
[labelArray addObject:strLabel];
}
if(letterTimer == nil){
NSTimeInterval timeInt = self.timeInterval?:0.45;
letterTimer = [NSTimer scheduledTimerWithTimeInterval:timeInt target:self selector:@selector(startLetterAnimotion) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop]addTimer:letterTimer forMode:NSRunLoopCommonModes];
}
}
-(void)startLetterAnimotion{
static NSInteger stringIndex = 0;
static NSInteger arrayIndex = 0;
CGFloat startY = self.startX?:mainBoundsHeight*0.2;
CGFloat startX = self.startY?:mainBoundsWidth*0.2;
NSString *currentString = self.letterArray[arrayIndex];
if(stringIndex>=currentString.length){
arrayIndex ++;
if(arrayIndex==self.letterArray.count){
[letterTimer invalidate];
letterTimer = nil;
return;
}
stringIndex = 0;
currentString = self.letterArray[arrayIndex];
}
UILabel *currentLabel = labelArray[arrayIndex];
NSMutableString *originString = [[NSMutableString alloc]init];
if(stringIndex>0&&stringIndex<currentString.length){
[originString appendString:currentLabel.text];
}
UIFont *letterFont = self.letterFont?:[UIFont systemFontOfSize:30];
[originString appendString:[NSString stringWithFormat:@"%@\n",[currentString substringWithRange:NSMakeRange(stringIndex, 1)]]];
CGSize stringSize = [originString sizeWithAttributes:@{NSFontAttributeName:letterFont}];
currentLabel.text = originString;
currentLabel.font = letterFont;
currentLabel.frame = CGRectMake(stringSize.width*arrayIndex+startX, startY, stringSize.width, stringSize.height);
if(stringIndex==0){
[parentsView addSubview: currentLabel];
}
stringIndex++;
}
@end