2017-08-27 39 views
0

我有一個UITextView某些單詞被下劃線替換爲填充空白效果。我在檢測這些「空白」上點擊時遇到困難。我到目前爲止所嘗試的是使用rangeEnclosingPosition的「粒度設置爲Word」來獲取單詞的範圍,但看起來它不能識別特殊字符上的點擊。現在,我正在尋找給我的'下劃線'字符串自定義屬性,所以我可以檢查,看看是否有任何自定義屬性設置。任何想法都會很有幫助。如何檢測UITextView下劃線的水龍頭?

回答

0

您可以嘗試使用UITextViewDelegate方法 - textViewDidChangeSelection通知時插入符號的文本視圖的位置發生變化,使你的邏輯在這裏如果從插入符號的當前位置的下一個字符是你的特殊字符。

+0

我想檢測一個特殊字符的水龍頭。鍵入一個特殊的字符本來就很容易:D – genaks

+0

我會在這裏發佈我在短時間內做的事:) – genaks

0

以下是我如何做到的 -

將自定義屬性添加到文本中的特殊字符。就我而言,我知道特殊字符將全部是下劃線,或者這只是我所尋找的。

NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:underscoreString attributes:@{ @"yourCustomAttribute" : @"value", NSFontAttributeName : [ UIFont boldSystemFontOfSize:22.0] }]; 

爲了尋找水龍頭上的特殊字符,按以下方式添加UITapGestureRecognizer - -

UITapGestureRecognizer *textViewTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedTextView:)]; 
textViewTapRecognizer.delegate = self; 
[self.textView addGestureRecognizer:textViewTapRecognizer]; 

,並以下列方式確定其選擇,所以我通過以下方式添加自定義屬性 -

-(void) tappedTextView:(UITapGestureRecognizer *)recognizer 
{ 
UITextView *textView = (UITextView *)recognizer.view; 

// Location of the tap in text-container coordinates 

NSLayoutManager *layoutManager = textView.layoutManager; 
CGPoint location = [recognizer locationInView:textView]; 
location.x -= textView.textContainerInset.left; 
location.y -= textView.textContainerInset.top; 

// Find the character that's been tapped on 

NSUInteger characterIndex; 
characterIndex = [layoutManager characterIndexForPoint:location 
             inTextContainer:textView.textContainer 
       fractionOfDistanceBetweenInsertionPoints:NULL]; 
NSString *value; 
if (characterIndex < textView.textStorage.length) { 
    NSRange range; 
    value = [[textView.attributedText attribute:@"yourCustomAttribute" atIndex:characterIndex effectiveRange:&range] intValue]; 
    NSLog(@"%@, %lu, %lu", value, (unsigned long)range.location, (unsigned long)range.length); 
} 
} 

如果您得到一個值,您的特殊字符被點擊。可以有更好的方法來做到這一點,但現在這對我來說很有效。