我可以获得NSAttributedString中元素的位置吗?

时间:2015-02-12 07:52:11

标签: ios nsattributedstring

enter image description here

我使用NSAttributeString来获取上面的内容(包括普通文本,带下划线的文本和图像),现在我想要做:如果用户点击带下划线的文本区域,我会做一些特殊的操作(打开网页或者...... )。现在我已经可以获得触摸的位置,但是我可以找到带下划线的文本的位置(或区域)吗?所以我可以使用两个区域来判断分接位置是否位于下划线文本上?

3 个答案:

答案 0 :(得分:1)

根据我的理解,您可以使用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可编辑(否),可选(是),链接是可选的

Please tick following properties from textview

希望它会帮助你......!

答案 1 :(得分:0)

你可以在属性字符串中使用html字符串,如下所示:

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType } documentAttributes:nil error:nil];

答案 2 :(得分:0)

使用UITextView它很容易实现。在textview上添加点按手势,当点击textview时检查是否点击特定字符。

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