• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

[复制链接]
菜鸟教程小白 发表于 2022-12-12 19:19:45 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我想知道如何以编程方式将 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap