比如我有一行
This is a test
点击每个单词后,它会发出相应的声音。现在通过不同的方法来实现它,我发现了 NSMutableAttributedString
。您可以为单个单词添加属性,如图像或字体等。我的问题是,是否有任何属性可以为一组字母添加声音。或者你能建议更好的方法吗?任何帮助表示赞赏。
最佳答案
使用 Attribute 字符串,您可以为每个单击的单词调用您的方法,然后您可以在识别单词后播放相应的声音。 属性字符串允许您添加自定义属性,然后识别不同的词类别并相应地应用不同的操作
首先添加识别器
UITapGestureRecognizer *singleFingerTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(textTapped:)];
然后在你的方法中
- (void)textTapped:(UITapGestureRecognizer *)recognizer
{
UITextView *textView = (UITextView *)recognizer.view;
// Location of the tap in text-container coordinates
NSLayoutManager *layoutManager = textView.layoutManager;
CGPoint location = [recognizer locationInView:textView];
location.x -= textView.textContainerInset.left;
location.y -= textView.textContainerInset.top;
NSLog(@"location: %@", NSStringFromCGPoint(location));
// Find the character that's been tapped on
NSUInteger characterIndex;
characterIndex = [layoutManager characterIndexForPoint:location
inTextContainer:textView.textContainer
fractionOfDistanceBetweenInsertionPoints:NULL];
if (characterIndex < textView.textStorage.length) {
NSRange range;
NSDictionary *attributes = [textView.textStorage attributesAtIndex:characterIndex effectiveRange:&range];
NSLog(@"%@", NSStringFromRange(range));
}
}
enter code here
如果你添加了服装属性
[paragraph addAttribute:@"hashtag" value:@(YES) range:wordRange];
你可以找到它
NSDictionary *attributes = [textView.textStorage attributesAtIndex:characterIndex effectiveRange:&range];
//Based on the attributes, do something
if ([attributes objectForKey:@"hashtag"]) {
NSLog(@"hashtag");
NSLog(@"clicked: %@",[textView.text substringWithRange:range] );
}
关于ios - 带有声音/音频的 NSMutableAttributedString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32051860/