gpt4 book ai didi

objective-c - 如何以编程方式将 UI 元素添加到现有的 nib 文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:50:44 26 4
gpt4 key购买 nike

我想知道如何以编程方式将 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 文件中呢?

最佳答案

正如 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com