Jay Mehta Jay Mehta - 3 months ago 4x
Objective-C Question

How to use TTTAttributedLabel with '@' and '#'?

When ever in text '@' symbol come like in twitter i need that portion clickable using TTTAttributeLabel. Like example : "hi @test hello text".
Only @test part clickable. TTTAttributeLabel class i am using in uitableview cell so that table didSelectedRowAtIndexPath method call when ever user press other part of label means not click on '@test'.

Thanks in advance.


You can use code sample from this question (see highlightMentionsInString: function)

Then add this code to your tableView:cellForRowAtIndexPath::

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
      MyCell *cell;
      // configure your cell
      // ...
      cell.attributedLabel.delegate = self;
      cell.attributedLabel.userInteractionEnabled = YES;
      cell.attributedLabel.text = someText;
      [self highlightMentionsInLabel:cell.attributedLabel]
      return cell;

 - (void)highlightMentionsInLabel:(TTTAttributedLabel *)attributedLabel {
      NSString *text = attributedLabel.text;
      NSRegularExpression *mentionExpression = [NSRegularExpression regularExpressionWithPattern:@"(?:^|\\s)(@\\w+)" options:NO error:nil];
      // and so on, use code from question I linked above
      // ...

 # pragma mark - TTTAttributedLabelDelegate

 - (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
     // your code here to handle `user:username` links

If you want different behaviour when user/hashtag taped, you'll need to implement separate highlightTagsInLabel: method for #hashtags, with different regexp and different urls (for example tag:tag_string) and call it after highlightMentionsInLabel: