I've UILabel which has some text and 2 month names like "In the month of January and July, sun shine will be peak" I sub classed UILabel and added touch event to it. Now I want to get the word below the text where user touched and find out whether user touched January/July or not. Is it possible?
Swift5 UILabel Extension. Use this code in that case. Show activity on this post. Change the text property to attributed and select the text and right click to get the font property. Click on the strikethrough.
If needed, it is possible to make UILabel clickable in Swift although it is recommended to use UIButton instead. To make UILabel clickable in Swift, you will need to create a UITapGestureRecognizer and then add it to a label.
A view that displays one or more lines of informational text.
I think you'll find what you're looking for in the documentation for UITextInputProtocol.
For some more high level information, check out Apple's Text, Web and Editing Guide, specifically in the section titled "A Guided Tour of a UITextInput Implementation". It discusses how you can create indexed positions in text, and ask touches what text position they've landed nearest.
Apple's references a sample projected called SimpleTextInput
, but I can't seem to find it. I'll keep looking.
I handled this problem by putting transaparent UIViews on top of the UILabel which were wired to handle touch events. You can adjust the position and size of the hit zone labels by calculating the size of the relevant portions of text. This approach also has the advantage of being able to tweak the sizes of your hit zones to make them bigger and so easier to tap with fat fingers.
I've implemented your question, just for fun on my blog.
Simply i've subclassed UILabel
adding touchEnded
, to recognize touch position and letter position.
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[touches allObjects] objectAtIndex:0];
CGPoint pos = [touch locationInView:self];
int sizes[self.text.length];
for ( int i=0; i<self.text.length; i++ )
{
char letter = [self.text characterAtIndex:i];
NSString *letterStr = [NSString stringWithFormat:@"%c", letter];
CGSize letterSize = [letterStr sizeWithFont:self.font];
sizes[i] = letterSize.width;
}
int sum = 0;
for ( int i=0; i<self.text.length; i++)
{
sum += sizes[i];
if ( sum >= pos.x )
{
[ _delegate didLetterFound:[ self.text characterAtIndex:i] ];
return;
}
}
}
Hope this helps
cheers.
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