Tap Gesture on part of UILabel

余生颓废 提交于 2019-11-28 11:29:21

You could try https://github.com/mattt/TTTAttributedLabel and add a link to the label. When the link is pressed you get a action, so part of the label click works only thing you have to would be customizing the link part of the label. I tried this in the past and it worked flawlessly but my client was not interested in using a third party component so duplicated this functionality using UIWebView and HTML.

Try this. Let your label be label :

  //add gesture recognizer to label
  UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] init];
  [label addGestureRecognizer:singleTap];
  //setting a text initially to the label
  [label setText:@"hello world i love iphone"];

 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 {

UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self.view];

CGRect rect = label.frame;
CGRect newRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width/2, rect.size.height);

if (CGRectContainsPoint(newRect, touchPoint)) {
    NSLog(@"Hello world");
}
}

Clicking on the first half of label will work (It gives log output). Not the other half.

Here is a light-weighted library specially for links in UILabel FRHyperLabel.

To achieve an effect like this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque quis blandit eros, sit amet vehicula justo. Nam at urna neque. Maecenas ac sem eu sem porta dictum nec vel tellus.

use code:

//Step 1: Define a normal attributed string for non-link texts
NSString *string = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque quis blandit eros, sit amet vehicula justo. Nam at urna neque. Maecenas ac sem eu sem porta dictum nec vel tellus.";
NSDictionary *attributes = @{NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]};

label.attributedText = [[NSAttributedString alloc]initWithString:string attributes:attributes];


//Step 2: Define a selection handler block
void(^handler)(FRHyperLabel *label, NSString *substring) = ^(FRHyperLabel *label, NSString *substring){
    NSLog(@"Selected: %@", substring);
};


//Step 3: Add link substrings
[label setLinksForSubstrings:@[@"Lorem", @"Pellentesque", @"blandit", @"Maecenas"] withLinkHandler:handler];

One option would be to use a non-editable UITextView instead of a UILabel. Of course this may or may not be a suitable solution depending on your exact needs.

This is basic code for how can add UITapGestureRecognizer to your control;

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];        
[MyLabelName addGestureRecognizer:singleTap];        
[self.view addSubView:MyLabelName]

This is method that call when you tapped your MyLabelName;

-(void)handleSingleTap:(UILabel *)myLabel
{
    // do your stuff;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!