替换UITextView中的文本 [英] Replacing Text in a UITextView

查看:471
本文介绍了替换UITextView中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个小的概念应用程序,读取字符流作为用户在UITextView中输入,当某个字被输入时,它被替换(类似于自动校正)。

i'm trying to write a little concept app which reads the character stream as the user types in a UITextView, and when a certain word is entered it is replaced (sort of like auto-correction).

我调查了使用 -

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

但是到目前为止我没有运气。任何人都可以给我一个提示。

but so far i had no luck. can anyone give me a hint.

非常感谢!

david

推荐答案

这是正确的方法。是否将其对象设置为 UITextView 的委托?

That is the correct method. Is its object set as the delegate of the UITextView?

UPDATES:

- 固定在上面说UITextView(我以前有UITextField)

-added代码示例如下:

UPDATES:
-fixed above to say "UITextView" (I had "UITextField" previously)
-added code example below:

此方法实现在委托对象的UITextView(例如其视图控制器或应用程序委托):

This method implementation goes in the delegate object of the UITextView (e.g. its view controller or app 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;
}

这篇关于替换UITextView中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆