在我看来,您有两种选择:
1.核心文本属性
使用 Core Text,您可以在单词下划线并对其应用许多其他装饰。以下是为文本添加下划线的示例:
//Create a font
CTFontRef sysUIFont = CTFontCreateUIFontForLanguage(kCTFontSystemFontType,
24.0, NULL);
//Create a string
NSString *aString = @"Random text";
//Choose the color
CGColorRef color = [UIColor blueColor].CGColor;
//Single underline
NSNumber *underline = [NSNumber numberWithInt:kCTUnderlineStyleSingle];
//Pack the attributes into a dictionary
NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:
(id)sysUIFont, (id)kCTFontAttributeName,
color, (id)kCTForegroundColorAttributeName,
underline, (id)kCTUnderlineStyleAttributeName, nil];
//Make the attributed string
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:string
attributes:attributesDict];
现在这适用于为文本添加下划线,但我不确定如何随着歌词的进展动画下划线从一个单词移动到另一个单词。
2.自定义UIView下划线
现在你的第二个选择是创建一个自定义的子类 UIView 的下划线类。这很容易制作动画。你甚至不必为下划线创建一个单独的类(尽管我推荐它);您可以只创建一个 UIView 并使用如下动画将它从一个单词移动到另一个单词:
CABasicAnimation *underlineMove = [CABasicAnimation animationWithKeyPath:@"position"];
underlineMove.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
endPosition = CGPointMake((float)nextWord.x, (float)nextWord.y);
underlineMove.toValue = [NSValue valueWithCGPoint:endPosition];
underlineMove.duration = currentWord.duration;
[underlineView addAnimation:underlineMove forKey:@"animation"];