Tôi chỉ thực sự mở rộng những gì @matt đã nói với một ví dụ nhanh về cách thực hiện điều này. Bạn bắt đầu với hai nhãn, một nhãn trực tiếp trên đầu trang khác với cùng thuộc tính và sắp xếp. Sau khi cả hai nhãn được cấu hình và bạn đã sẵn sàng để tạo hiệu ứng động, tất cả những gì bạn phải làm là làm mờ nhãn trên cùng.
- (void)awakeFromNib
{
[super awakeFromNib];
[self.view setBackgroundColor:[UIColor blackColor]];
NSString *text = @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 100.0, 320.0, 200.0)];
[label1 setNumberOfLines:0];
[label1 setBackgroundColor:[UIColor clearColor]];
[label1 setAttributedText:[self randomlyFadedAttStringFromString:text]];
[self.view addSubview:label1];
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 100.0, 320.0, 200.0)];
[label2 setNumberOfLines:0];
[label2 setBackgroundColor:[UIColor clearColor]];
[label2 setTextColor:[UIColor whiteColor]];
[label2 setAttributedText:[[NSAttributedString alloc] initWithString:text]];
[self.view addSubview:label2];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[UIView animateWithDuration:1.0 animations:^{
[label2 setAlpha:0.0];
} completion:^(BOOL finished) {
[label2 removeFromSuperview];
}];
});
}
Sau đó tạo chuỗi đặc biệt cho nhãn dưới cùng. Chuỗi được phân bổ này không được sửa đổi bất kỳ thuộc tính nào mà bạn đã đặt trên nhãn khác ngoài thuộc tính NSForegroundColorAttributeName
. Bạn có thể hoặc có thể không muốn đưa ra một thuật toán nào đó để xác định những chữ cái nào sẽ bị mờ dần bởi số tiền, nhưng đoạn mã dưới đây sẽ tạo ra một chuỗi được gán từ một chuỗi đầu vào, trong đó mỗi chữ cái alpha chỉ là một giá trị ngẫu nhiên giữa 0 và 1.
- (NSAttributedString *)randomlyFadedAttStringFromString:(NSString *)string
{
NSMutableAttributedString *outString = [[NSMutableAttributedString alloc] initWithString:string];
for (NSUInteger i = 0; i < string.length; i ++) {
UIColor *color = [UIColor colorWithWhite:1.0 alpha:arc4random_uniform(100)/100.0];
[outString addAttribute:NSForegroundColorAttributeName value:(id)color range:NSMakeRange(i, 1)];
}
return [outString copy];
}
Nguồn
2014-04-13 22:00:32
Cảm ơn! Ý tưởng tuyệt vời. Tôi chưa từng làm việc với CADisplayLink trước đây. – NatashaTheRobot