ios - UITextView textViewDidChangeSelection 被调用两次

标签 ios nsarray uitextview avaudioplayer

我有什么:

TextView

NSArray(字符串)

AVAudioplayer(尚未实现)

当我在 TextView 中选择一个单词时:

• 检查数组中是否存在单词

• 启动具有关联声音的音频播放器

不幸的是,当我点击两次以选择 TextView 中的单词时,textViewDidChangeSelection 被调用两次。我不知道为什么我看到“Youpie”两次。

我刚刚更改了 inputView 以隐藏键盘,因为我只需要在选择模式下使用 TextView。

- (void)textViewDidChangeSelection:(UITextView *)tve;
{
    NSString *selectedText = [tve textInRange:tve.selectedTextRange];
    if(selectedText.length > 0)
    {
        for (NSString *text in textArray)
        {
            if ([selectedText isEqualToString:text])
            NSLog(@"Youpie");
            tve.selectedTextRange = nil;
            if (ps1.playing == YES)
            {
                [self stopEveryPlayer];
                [self updateViewForPlayerState:ps1];
            }
            else if ([ps1 play])
                {
                    [self updateViewForPlayerState:ps1];
                    fileName.text = [NSString stringWithFormat: @"%@ (%d ch.)", [[ps1.url relativePath] lastPathComponent], ps1.numberOfChannels, nil];
                }
                else
                    NSLog(@"Could not play %@\n", ps1.url);
            break;
            }
        }
    }
}

- (void)awakeFromNib
{  
    textArray = [[NSArray alloc] initWithObjects:@"dog",@"cat",@"person",@"bird",@"mouse",  nil];
    textView.inputView = [[[UIView alloc] initWithFrame:CGRectZero]  autorelease];
    textView.delegate = self;
// ...
}

当我双击文本中的每个好词时,我注意到了一些事情。

textViewDidChangeSelection

如果已经选择了一个单词并且没有选择任何操作,我有 1 个“Youpie”。

如果没有的话,我有2个“Youpie”。

我找到了一个简单的解决方案。我在获取值后删除了 selectedRange 。 textViewDidChangeSelection 调用一次。

我改变了什么

tve.selectedTextRange = nil;

我使用 UITextView 的子类来禁用菜单。

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    return NO;
    return [super canPerformAction:action withSender:sender];
}

我也添加了 AVAudioPlayer (ps1) 的实现。

如果选择了已知单词,我的“自动播放”就会起作用:)

最佳答案

我不知道为什么该方法被调用两次或如何防止这种情况,但替代解决方案可能是在编辑菜单中显示一个附加项目,当单词是双倍时,该项目会在 TextView 中弹出点击。然后,可以从该附加菜单项中定义的操作选择器触发基于单词启动声音的操作。在此设计中,您将删除 textViewDidChangeSelection,因此不会被调用两次。请参阅http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/AddingCustomEditMenuItems/AddingCustomEditMenuItems.html有关修改标准菜单的一些附加信息。

关于ios - UITextView textViewDidChangeSelection 被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16107962/

相关文章:

ios - 如何访问 Swift 中应用程序包中包含的文件?

javascript - 在 iOS 设备中查看 Phonegap 的控制台日志

iOS NSArray objectAtIndex 越界

ios - 在IOS中解析嵌套的JSON代码

objective-c - iOS:带有多行 UITextView 的 UIAlertView

ios - 动画 UITextView 宽度溢出

ios - 当我从多个 UIImageView 显示中点击 UIImageView 时,未调用 touchesBegan 方法,与移动设备中的图库相同

ios - 如何将pod添加到本地pod项目

cocoa-touch - 想要使用 UISwipeGesture 在 NSArray 中的图片之间平滑过渡或滑动

c# - Xamarin iOS - UITextView 通过区域限制