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 quesion 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.
views:
130answers:
2
+2
A:
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.
Remover
2010-07-03 00:37:49
quick and simple, Thanks so much, you saved me some serious time.
TaoStoner
2010-07-03 00:51:46
One note, you have to make sure you check "User Interaction Enabled" in interface builder, or this won't work.
midas06
2010-07-23 04:18:16
I hit one problem with this method. It worked fine when the view controller was loaded directly, but when i created a nav controller, pushed the controller containing the label to the nav controller and then displaying it, the touches don't seem to get to the label anymore. Any Ideas?
midas06
2010-07-23 14:03:57
if it's the same view controller class that you're pushing it should work. sounds like there may be some other little problem. maybe start another question and post some code
Remover
2010-07-23 15:04:06
+2
A:
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.
Eiko
2010-07-03 00:48:42
I agree, the custom button type should give you a UILabel type user experience.
stitz
2010-07-03 05:36:38
+1, nice and simple. I had tried this before by setting a normal button to opactiy 0 which did not work, but the tip to change the type to custom worked perfectly.
bmoeskau
2010-08-12 06:22:05
The opacity will effect the button and all of its subviews, so opacity=0 will make the whole thing invisible.
Eiko
2010-08-14 10:58:45