彈幕效果展示:
步驟:
1.
在AppDelegate類裏面創建一個視圖控制器,並把創建的視圖控制器放入父視圖中。
其中關於用[self.window addSubview:viewController.view]
和self.window.rootViewController = viewController;請看我的上一篇文章:http://blog.csdn.net/u012989536/article/details/47979875
2.
然後的步驟就需要我們好好地思考一下,做任何一件事都要做好計劃,首先要確定要在我們創建的視圖裏面添加label 標籤:設置標籤的顏色這裏不過多說。代碼有註釋。
值得注意的是,我們的標籤是並不是一個。而是一些標籤進行循環的滾動,怎麼達到這個效果呢。首先我們不能直接在viewDidLoad裏面直接創建,以爲這樣不利於重複的生成,我們應該把它寫在一個函數裏面,以有利於我們調用。。於是有了這樣一段代碼:
//需要改變的三個地方,label :文本顏色,位置,文本的內容。
-(void)initDate
{
///只要有肉眼能看到的視圖,都是以ui開頭的
//實例化一個標籤,(用於現實文字)
UILabel *label = [[UILabel alloc]init];
//指定位置和大小。
label.frame =CGRectMake(480, rand()%290, 250, 30);
label.text = @“hello world”;
label.textColor = [UIColor redColor];
//將label加入本視圖中去。
[self.view addSubview:label];
}
*3.
然後我們應該調用一個每隔一段時間就會產生一個label標籤的方法。這樣
- (void)viewDidLoad
{
[super viewDidLoad];
//設置一個計時器,每隔一段時間就會產生一個label
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(initDate) userInfo:nil repeats:YES];
}
4.
做到這個步驟,我們就能夠看出一些效果,因爲label會不停的增加。那怎麼讓它滾動起來呢?
這時候就需要我們寫一個move的方法,來控制label的移動。這時候就會用到UIView 的animateWithDuration
方法:
(1):首先我們可以新建一個plist文件,用來存儲需要顯示的label,plist最好格式爲數組類型的。
(2):然後定義一個數組。用來存儲plist裏面的數據,並創建一個NSSstring類型的字符串用來接受。然後label以字符串的形式進行顯示到view上面:代碼如下:
//需要改變的三個地方,label :文本顏色,位置,文本的內容。
-(void)initDate
{
NSString *str = [array objectAtIndex:rand()%array.count];
///只要有肉眼能看到的視圖,都是以ui開頭的
//實例化一個標籤,(用於現實文字)
UILabel *label = [[UILabel alloc]init];
//指定位置和大小。
label.frame =CGRectMake(480, rand()%290, 250, 30);
label.text = str;
label.textColor = [UIColor randomColor];
//將label加入本視圖中去。
[self.view addSubview:label];
//讓生成的label傳入下面的move函數中去。
[self move:label];
}
-(void)move:(UILabel*)_label
{
[UIView animateWithDuration:5 animations:^{
_label.frame = CGRectMake(-250, _label.frame.origin.y, _label.frame.size.width, _label.frame.size.height);
} completion:^(BOOL finished) {
[_label removeFromSuperview];
}
];
}
//從這個方法開始添加(裝修)視圖已經加載到內存中。
- (void)viewDidLoad
{
[super viewDidLoad];
//讀取plist文件
NSString *path = [[NSBundle mainBundle ]pathForResource:@"彈幕" ofType:@"plist"];
array = [[NSArray alloc]initWithContentsOfFile:path];
//設置一個計時器,每隔一段時間就會產生一個label
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(initDate) userInfo:nil repeats:YES];
}
+ (UIColor *)randomColor
{
/*
顏色有兩種表現形式 RGB RGBA
RGB 24
R,G,B每個顏色通道8位
8的二進制 255
R,G,B每個顏色取值 0 ~255
120 / 255.0
*/
CGFloat r = arc4random_uniform(256) / 255.0;
CGFloat g = arc4random_uniform(256) / 255.0;
CGFloat b = arc4random_uniform(256) / 255.0;
return [UIColor colorWithRed:r green:g blue:b alpha:1];
}