问题
Right Now I am making an iOS app and I would like to implement the ability to remove letters in a UILabel by simply "Dropping the letter". The part That I am having an issue with is adding a gesture recognizer to individual letters of a UILabel. I have already searched the web for this and have nothing.Just to be clear, I am NOT adding a gesture recognizer to the whole label, I am only wanting to add it to individual letters. Any help is greatly appreciated.
Thanks
回答1:
It seems that the easiest way to do it is by dynamically calculating the position of a letter. Use this:
CGSize textSize = [text sizeWithFont:[UIFont boldSystemFontOfSize:size]
constrainedToSize:constrainedSize
lineBreakMode:NSLineBreakByWordWrapping];
so you can get the the size for a letter in the font and size you are using for each label and using the [stringInstance length]
property and the [UILabel numberOfLines]
property to get the approximate center for each letter in a label, then use a simple tapGestureRecognizer for each label and in there calling your method for
- (NSString*)letterForPoint:(CGPoint)tapCenter inLabel:(UILabel*)label;
there you use everything to calculate the approximate center for each letter and adding a selectableRange for error and correct user responding as x +- 20 pixels and y +- 20 pixels.
Apple says that anything with a selectable bound lesser than 40 pixels for 40 pixels will be completely annoying for the user, so your font size should actually be quite big for user interaction.
回答2:
If I am understanding correctly, it sounds like subclassing UILabel would make sense.
Make a LetterLabel: UILabel
class
and in the init set up your GestureRecognizer on self.
Then when you create your letters each one will have the recognizer attached to it
LetterLabel *firstLetter = [[LetterLabel alloc] init]
LetterLabel *secondLetter = [[LetterLabel alloc] init]
回答3:
UIGestureRecognizer can only be applied to a UIView or subclass of that (e.g. a UILabel, like Adam suggested). If you are worried about performance, then I think your next step would be to:
1) Subclass UIView in order to create a custom implementation of a UILabel-like view.
2) Draw out the custom label's string to in the drawInRect: method
3) Use the touchesBegan:withEvent:, touchesMoved:withEvent:, and touchesEnded:withEvent: methods to track finger positions in order to move/redraw characters of the backing string.
EDIT:
Alternatively, you could use one UIPanGestureRecognizer on a the custom label to track finger positions, and move around sublayers within the bounds of the custom label (each sublayer could contain a character in the string). In this way, you could more easily take advantage of Core Animation to animate the characters (i.e. create the "dropping" effect).
来源:https://stackoverflow.com/questions/13654766/add-uigesturerecognizer-to-individual-letters-of-uilabel