Tap action on some part of attributed string in iOS

1.4k views Asked by At

I want to give a tap action on part on a UILabel. For ex: If we have string like "My name is XYZ", in this case I want to add tap action for "XYZ" only.

How to do that in iOS (swift)

2

There are 2 answers

1
Rahul Shirphule On

There is control call TTTAttributedLabel which can handle the same in Objective-C So you can use that,

TTTAttributedLabel *tttLabel = <# create the label here #>;
NSString *labelText = @"Lost? Learn more.";
tttLabel.text = labelText;
NSRange r = [labelText rangeOfString:@"Learn more"];
[tttLabel addLinkToURL:[NSURL URLWithString:@"action://show-help"] withRange:r];

Then, in your TTTAttributedLabelDelegate:

- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
if ([[url scheme] hasPrefix:@"action"]) {
    if ([[url host] hasPrefix:@"show-help"]) {
        /* load help screen */
    } else if ([[url host] hasPrefix:@"show-settings"]) {
        /* load settings screen */
    }
} else {
    /* deal with http links here */
}}

For Swift you can do some thing like,

let name = "tomo"
let string = "My name is \(name)"
label.text = string
let nsString = string as NSString
let range = nsString.rangeOfString(name)
let url = NSURL(string: "action://users/\(name)")!
label.addLinkToURL(url, withRange: range)
0
Randy On

What about setting your label in a UIView next to a UIButton ?

UIView *view = [UIView new];
UILabel *label = [UILabel new];
UIButton *button = [UIButton new];

Add these constraints to view :

|[label][button]|

label.text = @"My name is"
[button setTitle:yourName forState:UIControlStateNormal];

By setting your label and your button's background colors to clearColor and your view's background ground to whiteColor ( for instance ) your shouldn't see that much difference.