iphone - 替换 UITextView 中的文本

标签 iphone cocoa-touch

我正在尝试编写一个小概念应用程序,当用户在 UITextView 中键入时读取字符流,并且当输入某个单词时它会被替换(有点像自动更正)。

我研究过使用 -

(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;

但到目前为止我还没有运气。谁能给我一个提示。

非常感谢!

大卫

最佳答案

这才是正确的方法。它的对象是否设置为UITextView的委托(delegate)?

更新:
- 修复了上面的“UITextView”(我之前有“UITextField”)
-添加了以下代码示例:

此方法实现位于 UITextView 的委托(delegate)对象中(例如其 View Controller 或应用程序委托(delegate)):

// replace "hi" with "hello"
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    // create final version of textView after the current text has been inserted
    NSMutableString *updatedText = [[NSMutableString alloc] initWithString:textView.text];
    [updatedText insertString:text atIndex:range.location];

    NSRange replaceRange = range, endRange = range;

    if (text.length > 1) {
        // handle paste
        replaceRange.length = text.length;
    } else {
        // handle normal typing
        replaceRange.length = 2;  // length of "hi" is two characters
        replaceRange.location -= 1; // look back one characters (length of "hi" minus one)
    }

    // replace "hi" with "hello" for the inserted range
    int replaceCount = [updatedText replaceOccurrencesOfString:@"hi" withString:@"hello" options:NSCaseInsensitiveSearch range:replaceRange];

    if (replaceCount > 0) {
        // update the textView's text
        textView.text = updatedText;

        // leave cursor at end of inserted text
        endRange.location += text.length + replaceCount * 3; // length diff of "hello" and "hi" is 3 characters
        textView.selectedRange = endRange; 

        [updatedText release];

        // let the textView know that it should ingore the inserted text
        return NO;
    }

    [updatedText release];

    // let the textView know that it should handle the inserted text
    return YES;
}

关于iphone - 替换 UITextView 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1628422/

相关文章:

ios - “NSAttributedString对于自动调整大小无效,它必须具有单个跨接段落样式(或无)且具有非包装的lineBreakMode。”

ios - 以像素为单位的 UIImage 大小

ios - UITabBar Lifecycle 的方法不会从后台启动

iphone - 为 UISplitViewController 的 MasterView 添加 subview

iphone - 如何从 NSData 创建字节数组

iphone - 带括号的 NSDictionary 返回值

iphone - 什么是iOS的常驻和脏内存?

iphone - MKCoordinateRegion setRegion问题

iphone - 我的 NSXMLParser 代码中的漏洞在哪里?

objective-c - 从一个 NSMutableArray 中删除包含在另一个数组中的元素