【问题标题】:how to have one view controller for multiple nib files iphone如何让一个视图控制器用于多个 nib 文件 iphone
【发布时间】:2011-08-24 09:19:49
【问题描述】:

所以我整个上午都在试图弄清楚如何在方向更改时从一个视图控制器加载第二个 nib 文件,但我没有成功,这就是我来这里寻求帮助的原因。问题是我想在设备旋转时加载一个横向 nib 文件。我有这段代码到目前为止它不起作用:

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if (toInterfaceOrientation==UIInterfaceOrientationLandscapeRight || toInterfaceOrientation==UIInterfaceOrientationLandscapeLeft) {
        [self initWithNibName:@"myNibFile" bundle:nil];
    }
}

新笔尖未加载。在界面生成器中,我将文件所有者设置为此视图控制器,因此它应该可以工作。我也尝试过:[[NSBundle mainBundle] loadNibNamed:@"myNibFile" owner:self options:nil]; ,但我也没有运气你能提供一个关于如何从 initWithNibName 加载 nib 文件的示例或有用的链接吗?我好像在网上找不到。

非常感谢。

【问题讨论】:

  • 即使你实现了这一点,你的 outlet 都将重新连接到新 nib 中的视图组件,因此你在现有视图中设置的任何值(例如文本字段、按钮状态)都将一旦加载新的笔尖就会丢失。我建议在界面构建器中了解大小检查器的大小、定位和自动调整大小功能 - 通过正确设置这些功能可以让您的视图在旋转时自动调整其布局。

标签: iphone objective-c cocoa-touch


【解决方案1】:

为此,您已经创建了类的新实例。您不能在运行时更改视图控制器的 nib。

为什么要为一个视图控制器创建多个 nib 文件。只需在单个 nib 文件和用户中相应地创建多个视图。

【讨论】:

    【解决方案2】:

    在运行时更改控制器的 nib 根本不是一个好主意(甚至不确定这是否可能合法)。它可能导致 nib 在内存中悬空并最终导致内存泄漏。前段时间我遇到了同样的问题,发现不使用 IB 和 nibs 是最简单的方法(幸运的是我的观点不是很复杂)。

    解决方案是在代码中布局子组件并根据方向变化调整它们。我在 UIViewController 子类中做了以下操作-

    -(void) adjustLayout:(UIInterfaceOrientation)orientation
    {
        if(UIInterfaceOrientationIsPortrait(orientation))
        {
             mySubview1.frame = frameInAccordanceWithPortrait;
        }
        else
        {
            mySubview1.frame = frameInAccordanceWithPortrait;
         }
    }
    
    - (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
    {
        [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
        [self adjustLayout:toInterfaceOrientation];
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多