ios - 带有声音/音频的 NSMutableAttributedString

标签 ios swift

比如我有一行

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/

相关文章:

c# - 如何通过捏合来缩放游戏对象?

ios - 从collectionview中删除viewcontroller中的 subview (uiview)

ios - UICollectionView 中的多个单元格

ios - WKWebView 历史加载

ios - Swift 中具有单个泛型函数的多种错误类型的泛型错误处理

ios - 如何使用 MVVM 和 RxSwift 事件在 UIViewController 及其子 UIView 之间进行通信?

ios - SwiftUI 文本不会扩展为多行

swift - iOS Deep Link 不会从 AppDelegate 调用任何函数

swift - 关于使用管理器的 Alamofire 版本

ios - 必须为标识符注册一个 nib 或一个类,或者在 Storyboard中连接一个原型(prototype)单元