2016-06-22 7 views
-2

私はテキストビューを持っており、ユーザーがリンクをタイプすると色が変わるはずです。私は次のように試しました。UITextView iOSの範囲でテキストを置き換えるにはどうすればいいですか?

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { 
    if ([text rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].location != NSNotFound) { 
     NSString *stringWithNSDataDetector = [textView text]; 
     NSError *error = nil; 
     NSDataDetector * dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink 
                    error:&error]; 
     UIFont *fontNormal = [UIFont fontWithName:@"SFUIText-Light" size:18.0]; 
     __block NSMutableArray *allMatches = [[NSMutableArray alloc] init]; 
     [dataDetector enumerateMatchesInString:stringWithNSDataDetector 
            options:0 
            range:NSMakeRange(0, [stringWithNSDataDetector length]) 
           usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) 
     { 
      if ([match resultType] == NSTextCheckingTypeLink){ 
       [allMatches addObject:[match URL]]; 
       NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithString:[[match URL] absoluteString]attributes:nil]; 
       NSRange rangeOfUrl = NSMakeRange(0, [attributedString string].length); 
       [attributedString addAttribute:NSFontAttributeName value:fontNormal range:rangeOfUrl]; 
       [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorFromHexString:TEXT_FIELD_UNDERLINE_BLUE] range:rangeOfUrl]; 

       NSMutableAttributedString *finalizedStr = [[NSMutableAttributedString alloc]initWithString:self.postTxtView.text]; 

       [finalizedStr replaceCharactersInRange:rangeOfUrl withAttributedString:attributedString]; 
       self.postTxtView.attributedText = finalizedStr; 
      } 
     }]; 

     for (NSURL *url in allMatches) { 
      NSLog(@"%@", [url absoluteString]); 
     } 
    } 
    return YES; 
} 

このリンクはよくリンクを見つけるために働いています。しかし、リンクが見つかるとスペースボタンを押すと、そのリンクだけが色付けされます。私は enter image description here

がどのように私はこの問題を解決するスペースキーを押した後、私はスペース enter image description here

を押す前に

答えて

0

自分で交換する場合は、NOを返して、発信者が交換しないようにする必要があります。あなたのコードで

0

ルック:

NSRange rangeOfUrl = NSMakeRange(0, [attributedString string].length); 
NSMutableAttributedString *finalizedStr = [[NSMutableAttributedString alloc]initWithString:self.postTxtView.text]; 
[finalizedStr replaceCharactersInRange:rangeOfUrl withAttributedString:attributedString]; 
self.postTxtView.attributedText = finalizedStr; 

だから、最初の行は、そのlocationゼロある範囲で始まる - それは、文字列の先頭です。その範囲でアトリビュートされた文字列を挿入します。つまり、の文字列の開始に挿入します。その後、テキストビューのテキスト全体を置き換えるので、色付きのURLはに表示され、テキストの先頭にはと表示されます。

+0

これを機能させるには、変数にURL範囲を保持し、その範囲でテキストを置き換える必要があります。右? – codebot

+0

私が言ったことを読んだことがありますか? '0'は間違っています。あなたは 'match'によって表されるURLを見ていますが、全体的な文字列' match '_isのどこを見ていません。 – matt

関連する問題