4

I have a bunch of UILabels that I add through code and I want to perform a specific action for each if the user's finger touches up inside (much like UIButton's touchUpInside in IB). What is the best way of doing this?

willcodejavaforfood
  • 43,223
  • 17
  • 81
  • 111
Don Wilson
  • 558
  • 2
  • 8
  • 21

2 Answers2

18

The easiest way is probably to use UIButton instead of UILabel. A custom UIButton has no border and can look like a plain label, but handles the event tracking for you.

Otherwise, you must derive from UILabel and implement the UIResponder calls for touch handling.

drawnonward
  • 53,459
  • 16
  • 107
  • 112
  • 1
    To make a button behave more like a lable, you may need multi-line text with wrapping in a button. See this answer for that: http://stackoverflow.com/questions/604632/how-do-you-add-multi-line-text-to-a-uibutton – RajV Sep 19 '13 at 14:44
  • Note that UIButton doesn't work well with text wrapping and sometimes a UILabel is necessary. – David Rector Feb 15 '19 at 03:51
5

You can use UITapGestureRecognizer to perform action over the label Fields.

Set the number of taps and touches on the UITapGestureRecognizer object.

[oneFingerTwoTaps setNumberOfTapsRequired:1];
[oneFingerTwoTaps setNumberOfTouchesRequired:1]; 

set user interaction of label field like

labelField.userInteractionEnabled = YES;

then add target method over the

UITapGestureRecognizer object.
Pathetic Learner
  • 729
  • 1
  • 11
  • 21