我可以在NSAttributedString中獲取元素的位置嗎?
我用NSAttributeString得到的東西像上面(包括普通文本,下劃線的文字和圖像),現在我想要做的事:如果拍了拍下劃線的文本區域的用戶,我會做一些特殊動作(開網絡或某事)。現在我可以獲取觸摸的位置了,但是我可以找到加下劃線的文本的位置(或區域)嗎?所以我可以使用這兩個區域來判斷水龍頭位置是否位於下劃線文字上?
我可以在NSAttributedString中獲取元素的位置嗎?
我用NSAttributeString得到的東西像上面(包括普通文本,下劃線的文字和圖像),現在我想要做的事:如果拍了拍下劃線的文本區域的用戶,我會做一些特殊動作(開網絡或某事)。現在我可以獲取觸摸的位置了,但是我可以找到加下劃線的文本的位置(或區域)嗎?所以我可以使用這兩個區域來判斷水龍頭位置是否位於下劃線文字上?
您可以在屬性字符串使用HTML字符串是這樣的:
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType } documentAttributes:nil error:nil];
使用UITextView
很容易實現。在文本視圖上添加點按手勢,並在點擊文本視圖時檢查是否點擊特定字符。
textView.textContainerInset = UIEdgeInsetsZero;
[textView setContentInset:UIEdgeInsetsZero];
textView.attributedText = @"your attributedString";
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textTapped:)];
[textView addGestureRecognizer:tap];
添加手勢的實現方法
- (void)textTapped:(UITapGestureRecognizer *)recognizer
{
UITextView *textView = (UITextView *)recognizer.view;
/*--- Get range of string which is clickable ---*/
NSRange range = [textView.text rangeOfString:@"Your Clickable String"];
NSLayoutManager *layoutManager = textView.layoutManager;
CGPoint location = [recognizer locationInView:textView];
NSUInteger characterIndex = [layoutManager characterIndexForPoint:location inTextContainer:textView.textContainer fractionOfDistanceBetweenInsertionPoints:NULL];
if (characterIndex >= range.location && characterIndex < range.location + range.length - 1)
{
NSLog(@"Text Tapped:");
}
}
按我的理解,你可以的UITextView及其委託會有所幫助。
步驟1
{
NSURL *URL = [NSURL URLWithString: @"http://www.sina.com"];
NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:"Your text to display"];
[str addAttribute: NSLinkAttributeName value:URL range: NSMakeRange(0, str.length)];
_textview.attributedText = str;
}
步驟2 添加委託
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
NSLog(@"URL:: %@",URL);
//You can do anything with the URL here (like open in other web view).
[[UIApplication sharedApplication] openURL:URL];
return YES;
}
步驟3可編輯的(否),可選擇的(是),鏈接是可選的
希望它會幫助你..!
你使用了什麼組件? 'UITextView'或'UILabel'? – sikhapol 2015-02-12 07:56:03
現在,我正在使用UILabel來繪製NSAttributeString – ximmyxiao 2015-02-12 07:58:06
顯示和處理「UITextView」鏈接上的點擊會容易得多。請參閱http://stackoverflow.com/a/21630187/2168557關於如何使用鏈接的屬性字符串。然後在'UITextViewDelegate'中實現'textView:shouldInteractWithURL:inRange:'處理點擊鏈接。 – sikhapol 2015-02-12 08:03:00