ios - 使用 Storyboard从 xib 或其他场景添加 subview

标签 ios view storyboard

我是 iOS 和 Xcode 的新手。 我不知道如何设计一个单独的 View 并使用 Storyboard 将其添加到主 UIViewController 中。

我采用了不同的方法..

  1. 只需从 xcode 的右下角窗口中抓取一个 UI 对象,然后将它放到 Storyboard的任何空间区域。但是我不能像 xib 那样删除 UI 对象。
  2. 添加一个新的 UIViewController。在 UIViewController 中添加一个 View 。在主 ViewController.m 中,我在 viewDidLoad 中获取了新的 UIViewController 实例,然后是 [self.view addSubview:newUIViewController.view]。但是我看不到添加的 View 。
  3. 我创建了一个新的 xib 文件。并在其中添加一个 View 。我还尝试在主 ViewController 中获取实例。并且 addSubview 使用 xib 的 View 。但它也失败了。

是否有正确的方法或任何可行的解决方案?

最佳答案

我想出了一个办法。 描述如下:

  1. 创建一个 .xib 文件。例如:MyView.xib
  2. 创建一个 objective-c 类。例如:MyViewClass.h 和 MyViewClass.m
  3. 将 .xib 文件的所有者设置为类。
  4. 在 Storyboard上添加一个 UIView 元素,并将自定义类设置为 objective-c 类名 (MyViewClass)。
  5. 重点是覆盖object-c类中的initWithCoder方法。

    - (id)initWithCoder:(NSCoder *)aDecoder {
        if ((self = [super initWithCoder:aDecoder])) {
            [self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil] objectAtIndex:0]];
        }
        return self;
    }
    

想法是自定义类由 Storyboard加载并调用 initWithCode。 索引 0 是 .xib 界面构建器中的 Root View 。

这有点棘手,但它确实有效。

关于ios - 使用 Storyboard从 xib 或其他场景添加 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8754157/

相关文章:

iphone - 更改 UITextView 中所选单词/行的字体格式

java - 在Android中绘制动态自定义 View 棋盘

ios - 使用其他三个 View Controller 设置 UITabBarController

ios - 如何 merge 2 个 Storyboard与 git 中的冲突?

ios - 使用 UIViewControllerAnimatedTransitioning 而不使用 Storyboard Segues

ios - 适用于 3.5 和 4 英寸屏幕的应用程序底部的 iAd 横幅

android - 如何在 iOS 上注册 React Native 模块

javascript - 为什么couchdb的reduce是这样实现的呢?

mysql - 延迟评估 MySQL View

ios - 如何推送两个 View Controller 但只为第二个设置动画过渡?