iOS Instagram Tags Text Layout? How Is It Done?

China☆狼群 提交于 2019-12-05 21:58:16

Here is a simplified way to do it using UITextView and NSAttributedString:

  1. Use regular expressions to get character ranges for links.
  2. Add link styling to the matched ranges.
  3. Add custom attribute to range that references tap action to execute.
  4. On touch, if index of character is inside a matched range, change the link formatting to highlight it and run the associated tap action.

How to get index of character at location in iOS7:

- (NSUInteger) getCharIndexAt: (CGPoint) location
{
    NSLayoutManager *layoutManager = self.layoutManager;
    NSUInteger characterIndex = NSNotFound;
    characterIndex = [layoutManager characterIndexForPoint:location inTextContainer:self.textContainer fractionOfDistanceBetweenInsertionPoints:NULL];

    return characterIndex;
}

Also check out WWDC 2013 intro to TextKit Demo

ios7 text utilities

Larme

Well, I'm currently working on NSAttributedString and UITextView to get all this working, and my current code can do it. So I'm going to explain a possible version of doing this.
Here are the tips and big steps, with iOS7:
NSAttributedString, in iOS7 has a new attribute : NSLinkAttributeName. You can add it to your NSAttributedString, and with a detection method (combining: how to make #key and @key clickable in IOS7 and Get word from tap in UITextView) you can manage it. That's for the general way of doing it. For previous version, you'll have to do a little more of work, but keeping this general idea.
But since, it only for hashtags, since you can detect the world behind the tap, you can do this: Detect what word has been tapped (see previous links), detect if this word has an hashtag, and if yes, you can do whatever action you want. You can play with a NSRegularExpression to know where are the hashtags, and know when to "color" them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!