Handling Touch Event in UILabel and hooking it up to an IBAction
IosIphoneUilabelInterface BuilderTouch EventIos Problem Overview
Ok, so I have a UILabel
created in interface builder that displays some some default text of "tap to begin".
When the user taps the UILabel
I want it to trigger an IBAction method:
-(IBAction)next;
which updates the text on the label to say something new.
It would be really convenient if this allowed me to simply drag a connection from my method to my label and then select touch up inside, as with a button. but alas, no cigar.
so anyways, I guess my question is, am I going to have to subclass UILabel
to get this to work? Or is there some way I can drag a button over the label, but make it 0% opaque. Or is there a simpler solution I'm missing?
Ios Solutions
Solution 1 - Ios
Check it out:
UILabel *label = ...
label.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGesture =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(labelTap)];
[label addGestureRecognizer:tapGesture];
The trick is to enable user interaction.
Solution 2 - Ios
UILabel inherits from UIView which inherits from UIResponder. All UIresponder objects can handle touch events. So in your class file which knows about your view (which contains the UIlabel) implement:
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event;
In interface builder set the UILabel's tag value. when touches occur in your touchesBegan method, check the tag value of the view to which the tag belongs:
UITouch *touch = [touches anyObject];
if(touch.view.tag == MY_TAG_VAL)
label.text = @"new text";
You connect your code in your class file with the UILabel object in interface builder by declaring your UILabel instance variable with the IBOutlet prefix:
IBOutlet UILabel *label;
Then in interface builder you can connect them up.
Solution 3 - Ios
You can use a UIButton, make it transparent, i.e. custom type without an image, and add a UILabel on it (centered). Then wire up the normal button events.
Solution 4 - Ios
Swift 3
You have an IBOutlet
@IBOutlet var label: UILabel!
In which you enable user interaction and add a gesture recognizer
label.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(userDidTapLabel(tapGestureRecognizer:)))
label.addGestureRecognizer(tapGesture)
And finally, handle the tap
func userDidTapLabel(tapGestureRecognizer: UITapGestureRecognizer) {
// Your code goes here
}