UILabel
is only capable of displaying plain text strings (in iOS 6 it can now also display NSAttributedString
s, but this will not work in older iOS versions, so it is best not to rely on this), so you will not be able to do this with a label.
You can look at TTTAttributedLabel for displaying attributed text (so you can add underlines and other formatting), but you will not be able to add hyperlinks with this class.
The options you have for a clickable segment of the string are basically:
Use a plain UILabel
and overlay a UIButton
over the part that you want to be clickable, or
Use TTTAttributedLabel
to achieve the underline effect, and a UITapGestureRecognizer
to detect and handle taps (note that this will capture taps on the entire label, not just the underlined part).
For iOS 6:
UILabel *label = [[UILabel alloc] init];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"Tap here to read the latest Football News."];
[string addAttribute:NSUnderlineStyleAttributeName value:@(1) range:NSMakeRange(4, 4)];
label.attributedText = [string copy];
For earlier iOS versions as well as iOS 6:
TTTAttributedLabel *label = [[TTTAttributedLabel alloc] init];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"Tap here to read the latest Football News."];
[string addAttribute:NSUnderlineStyleAttributeName value:@(1) range:NSMakeRange(4, 4)];
label.text = [string copy];
Then add a gesture recogniser and implement handleTap:
:
UITapGestureRecognizer *recogniser = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[label addGestureRecognizer:recogniser];
- (void)handleTap:(UITapGestureRecognizer *)recogniser {
// Handle the tap here
}