简体   繁体   English

iOS-将UILabel从界面构建器连接到代码

[英]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. 我想在UILabel上设置自定义字体,我已经弄清楚该如何做。 My question is how do I access a UILabel that I created via the drag and drop interface builder in the code? 我的问题是如何访问通过代码中的拖放界面构建器创建的UILabel?

I've tried ctrl + clicking the UILabel and dragging it to the file's owner but it won't let me. 我已经尝试过ctrl +单击UILabel并将其拖动到文件的所有者,但是它不允许我这样做。 I also tried opening the assistant editor and connecting the UILabel directly to the corresponding .h file, but that won't work either. 我还尝试打开助手编辑器,并将UILabel直接连接到相应的.h文件,但这也不起作用。 How do I access the UILabel programatically?? 如何以编程方式访问UILabel? I know this should be really easy. 我知道这应该很容易。

// 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. 现在,在代码中使用IBOutlet标记,您应该能够从File的Owner拖动 IB中的标签 (而不是相反)。

Assuming you added the UILabel to your .xib file. 假设您将UILabel添加到了.xib文件中。 ctrl click the UILabel and dragged it to your .h file. ctrl单击UILabel并将其拖动到您的.h文件。 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. 使用您从.m文件中输入的标签名称进行访问。

By ctrl+click and dragging the UILabel from the .xib to the .h, you will basically add the UILabel as a property. 通过按ctrl键并单击并将UILabel从.xib拖到.h,基本上可以将UILabel添加为属性。 It will automatically added implementation of it in the .m file so you'll be good to go. 它会自动将其实现添加到.m文件中,因此您将可以正常使用。

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. 如果要随时修改UILabel,则需要在.h文件中声明它,并在计划修改它的.m文件中声明它。

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. 在您的.m文件中。 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. 完成此操作后,可以按照之前尝试的方式将实际变量链接到.xib文件中的物理标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM