I have a NSAttributedString like so:
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"testing it out @clickhere"];
NSInteger length = str.length;
[str addAttribute:NSForegroundColorAttributeName value:[UIColor bestTextColor] range:NSMakeRange(0,length)];
The NSMutableAttributedString gets set to a UILabel like so:
label.attributedText = str;
How do I make a tap gesture (or something clickable) to another viewcontroller for the words '@clickhere in the string above?
Thanks!
I think, the best way is adding the UIGestureRecognizer
to your UILabel
and validate the frame that you would like.
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[_yourLabel addGestureRecognizer:singleTap];
- (void)handleTap:(UITapGestureRecognizer *)tapRecognizer
{
CGPoint touchPoint = [tapRecognizer locationInView: _yourLabel];
//Modify the validFrame that you would like to enable the touch
//or get the frame from _yourLabel using the NSMutableAttributedString, if possible
CGRect validFrame = CGRectMake(0, 0, 300, 44);
if(YES == CGRectContainsPoint(validFrame, touchPoint)
{
//Handle here.
}
}
Simply first add a gesture to your label
[label setUserInteractionEnabled:YES];
UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
[label addGestureRecognizer:gesture];
control your gesture area in the below method
- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer
{
static CGRect touchableRect = CGRectMake(100.0f, 0.0f, 100.0f, 50.0f); // Give your rect as you need.
CGPoint touchPoint = [gestureRecognizer locationInView:self.view];
if (CGRectContainsPoint(touchableRect, touchPoint))
{
//User has tap on where you want. Do your other stuff here
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With