簡體   English   中英

如何檢測UITextView中下划線的敲擊?

[英]How to detect taps on underscores in a UITextView?

我有一個UITextView其中某些單詞被下划線替換,以填補空白效果。 我在檢測這些“空白”上的水龍頭時遇到困難。 到目前為止,我已經嘗試過使用Granularity設置為Word的rangeEnclosingPosition來獲取被敲擊的單詞的范圍,但是看起來它無法識別特殊字符的敲擊。 現在,我希望為我的“下划線”字符串提供自定義屬性,以便隨后可以查看是否點擊的單詞設置了任何自定義屬性。 任何想法都將對您有所幫助。

您可以嘗試使用UITextViewDelegate方法-textViewDidChangeSelection ,當插入符在文本視圖中的位置發生更改時得到通知,如果插入符當前位置的下一個字符是您的特殊字符,請在此處進行邏輯處理。

這是我的做法-

將自定義屬性添加到文本中的特殊字符。 就我而言,我知道特殊字符都是下划線,或者這僅僅是我要的內容。 因此,我通過以下方式添加了自定義屬性-

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);
}
}

如果您得到一個值,則說明您的特殊字符被點擊。 可能有更好的方法可以執行此操作,但現在對我而言有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM