How to make a string with multiple parts which can be touched in iOS?

188 views Asked by At

I want to create a string which consists of 3 parts:

  • the username
  • some static string
  • the post

For example: Thomas has liked Offical Stackoverflow Page

The user should be then able to click either on 'Thomas' which redirects him to the profile of Thomas or on 'Offical Stackoverflow Page' which redirects him to the post (somewhere inside the app). Of course the different parts can have different formats. A good example would be the facebook app, which shows some posts or likes.

I would do it with autolayout, but the app should be i18n-ized so it means the parts could change (stupid example: 'Official Stackoverflow Page is liked by Thomas').

Since I'm going to but these parts together, I thought I could use a NSAttributedString, which works perfectly for the layout, but I cannot add any action to it.

I read stuff like this: Add tap event to IOS NSMutableAttributedString. But really? Is that all? Isn't there any other way to do that?

I'd prefer a solution or idea working in swift (also if there are already some pods, i'd love to use them rather than re-inventing the wheel)

1

There are 1 answers

0
Mikael On

you can create a label for each text and do the following:

UILabel *label = ...
label.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGesture =
  [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTap)];
[label addGestureRecognizer:tapGesture];

then add each label to a container view with the proper layout constraints to align everything left or center...

Another idea is to do it through the storyboard with a container and 3 labels with constraints:

  • left = 0
  • top and bottom = 0
  • right = 1 (more or less to adjust spaces between words)

Then

  • Set 3 Segue on your controller, 1 for each action.
  • Setup a unique touch callback for the 3 labels.
  • In this callback, you will trigger the right Segue according to the touched Label.
  • And then, fill their content according to what you need to display.