Kyle Clegg
Kyle Clegg

Reputation: 39470

iOS - Connect UILabel from interface builder to code

I want to set a custom font on a UILabel, which I've figured out how to do just fine. My question is how do I access a UILabel that I created via the drag and drop interface builder in the code?

I've tried ctrl + clicking the UILabel and dragging it to the file's owner but it won't let me. I also tried opening the assistant editor and connecting the UILabel directly to the corresponding .h file, but that won't work either. How do I access the UILabel programatically?? I know this should be really easy.

Upvotes: 0

Views: 2067

Answers (3)

Mundi
Mundi

Reputation: 80265

// YourController.h

@interface YourController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *theLabel; 
@end

// YourController.m

@implementation
@synthesize theLabel; 
///....
@end

Now with the IBOutlet marker in your code you should be able to drag from File's Owner to the label (not the other way round) in IB.

Upvotes: 3

Karoly S
Karoly S

Reputation: 3258

If you want to modify the UILabel at any point, you need to declare it in the .h file, and the .m file where you plan to modify it.

When you declare it is should like roughly like:

@interface MyObject { 

UILabel *_testLabel;

}

@property (nonatomic, strong) IBOutlet UILabel *testLabel

Then of course you would do,

@synthesize testObeject = _testLabel;

in your .m file. After you've done this, you can link the actual variable to your physical label in your .xib file the way you were attempting to before.

Upvotes: 0

atbebtg
atbebtg

Reputation: 4083

Assuming you added the UILabel to your .xib file. ctrl click the UILabel and dragged it to your .h file. You will have to enter certain info including the name of the Label. Use the name of the label that you entered from y our .m file to access it.

By ctrl+click and dragging the UILabel from the .xib to the .h, you will basically add the UILabel as a property. It will automatically added implementation of it in the .m file so you'll be good to go.

Upvotes: 0

Related Questions