2009-10-27 5 views
3

UITextView에서 사용자가 입력 할 때 문자 스트림을 읽는 작은 개념의 앱을 작성하려고합니다. 특정 단어가 입력되면 대체됩니다 (자동 수정과 같은 정렬).UITextView에서 텍스트 바꾸기

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

을하지만, 지금까지 내가 운이 없었다 -

은 내가 사용으로 보았다. 누구나 내게 힌트를 줄 수 있어요.

크게 감사드립니다!

데이비드

+0

당신은 txtView : shouldChangeTextInRange : replacementText :? – Malaxeur

답변

11

올바른 방법입니다. 개체가 UITextView의 대리인으로 설정되어 있습니까?

UPDATES "UITextView를"말 위 - 고정
(I는 "UITextField에"이전에 있었다) 아래
걸러 코드 예제 :

이 방법은 구현이 UITextView의 위임 객체에 간다 (보기 컨트롤러 또는 앱 대리인) :

// 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; 
} 
+0

모든 것이 잘 연결되어 있습니다.이 메서드를 사용하여 지정된 문자열을 다른 문자열로 바꾸는 방법을 모르겠습니다. 감사 –