Sawsan
Sawsan

Reputation: 1114

Replace text in UITextView with linkable text - iOS

I have dynamic text that contains user name as place holder, I want to replace the place holder of user name with actual user name but I want this name to be linkable,in other words when I click on the user name it should perform a certain selector which redirects to the profile page. Is this doable?

This is my code:

NSString *originalText = @"go to :user profile or go to :place";
NSString *userText = @"Sawsan";
NSString *placeText = @"SomePlace";

originalText = [originalText stringByReplacingOccurrencesOfString:@":user"
                                                             withString:userText];
originalText = [originalText stringByReplacingOccurrencesOfString:@":place"
                                                             withString:placeText];
self.mainLabel.text = originalText;

/*
 * Result is: "go to Sawsan profile or go to SomePlace"
 */

Can I replace :user and :place with Sawsan and SomePlace that can perform different selector when the user click on any of them?

Upvotes: 0

Views: 107

Answers (1)

iCode
iCode

Reputation: 1466

Do it with a UITapGestureRecognizer:

self.mainLabel.userInteractionEnabled = YES;

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushAction)];
[self.mainLabel addGestureRecognizer:tap];

PushAction:

-(void)pushAction
{
    NSLog(@"mainLabel tapped");
}

Additionally I would do it like this with the user:

[NSString stringWithFormat:@"go to %@ profile", userText];

Upvotes: 1

Related Questions