OGeek|极客世界-中国程序员成长平台

标题: objective-c - 如何以编程方式将 UI 元素添加到现有的 nib 文件 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 19:19
标题: objective-c - 如何以编程方式将 UI 元素添加到现有的 nib 文件

我想知道如何以编程方式将 UI 元素添加到现有的 nib 文件中。

如果我在 loadView 方法中以编程方式创建 View 并添加如下代码,则标签会正确显示。

self.view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0,2,150,100)];

[self.view addView:lbl];

但是如何将标签添加到现有的 nib 文件中?



Best Answer-推荐答案


正如 Paul.s 指出的,您需要在 viewDidLoad 方法中执行您的自定义代码。

来自 Apple 文档。

This method is called after the view controller has loaded its associated views into memory. This method is called regardless of whether the views were stored in a nib file or created programmatically in the loadView method. This method is most commonly used to perform additional initialization steps on views that are loaded from nib files.

所以,在你的 Controller 中你可以这样做:

- (void)viewDidLoad
{
   [super viewDidLoad];

   // your other views here

   // call addSubview method on self.view
}

你为什么这样做?因为在这里您可以确定 View 已加载到内存中并且 socket 已正确设置。

相反,关于loadView方法

If you override this method in order to create your views manually, you should do so and assign the root view of your hierarchy to the view property. (The views you create should be unique instances and should not be shared with any other view controller object.) Your custom implementation of this method should not call super.

一个例子可以是:

- (void)loadView
{
    CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
    UIView *contentView = [[UIView alloc] initWithFrame:applicationFrame];
    contentView.backgroundColor = [UIColor whiteColor];

    self.view = contentView; 

    // call addSubview method on self.view
}

我建议你阅读View Controller Programming Guide for iOS .

希望对你有帮助。

关于objective-c - 如何以编程方式将 UI 元素添加到现有的 nib 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9175407/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4