我想在我的应用程序的右下角有一个持久的按钮。在所有 View 过渡期间,按钮应保持静态。我在确定将按钮添加到哪个 View 时遇到麻烦。我知道按钮应该存储在AppDelegate中,但是我不知道将其添加到窗口以外的其他 View 是什么。将其添加到窗口的一个缺点是,当有一个应用程序在后台运行时(例如,电话),添加的状态栏填充将向下推窗口。总的来说,将其添加到窗口中似乎是一个棘手的解决方案-有什么想法吗?

最佳答案

是的,将其添加到UIWindow会非常hacky和挑剔。

Storyboard

如果您使用的是Storyboards和iOS 5.0及更高版本,则应该能够使用容器 View 并执行以下操作:

这是另一张图片,显示了第一个View Controller的结构,虽然相当简单:

左侧的 View Controller 具有一个容器,然后是将按钮保持在其顶部的 View 。容器指示导航 Controller (直接在右侧)应出现在其自身内,该关系由=([])=>箭头(正式称为嵌入segue)显示。最终,导航 Controller 将其根 View Controller 定义为右侧的根 View Controller 。

总而言之,第一个 View Controller 在容器 View 中煎饼,其按钮位于顶部,因此内部发生的所有事情都必须将按钮置于顶部。

使用childViewControllers

又名“我讨厌 Storyboard 和小狗”模式

使用与Storyboard版本类似的结构,可以使用按钮创建基本 View Controller ,然后在其下方添加将成为应用程序新“根”的 View 。

为了清楚起见,让我们将持有按钮的一个 View Controller 称为FakeRootViewController,而实际上,该 View Controller 将成为应用程序的根:RootViewController。所有后续的 View Controller 甚至都不知道其他所有人之上都有FakeRootViewController

FakeRootViewController.m

// The "real" root
#import "RootViewController.h"

// Call once after the view has been set up (either through nib or coded).
- (void)setupRootViewController
{
    // Instantiate what will become the new root
    RootViewController *root = [[RootViewController alloc] <#initWith...#>];

    // Create the Navigation Controller
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:root];

    // Add its view beneath all ours (including the button we made)
    [self addChildViewController:nav];
    [self.view insertSubview:nav.view atIndex:0];
    [nav didMoveToParentViewController:self];
}

AppDelegate.m
#import "FakeRootViewController.h"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    FakeRootViewController *fakeRoot = [[FakeRootViewController alloc] <#initWith...#>];

    self.window.rootViewController = fakeRoot;
    [self.window makeKeyAndVisible];

    return YES;
}

这样一来,您便可以在窗口上插入按钮,而不会感到内,并且拥有“我真的应该成为一名程序员吗?”的所有好处。它造成的。

关于ios - 使按钮在所有 View Controller 中保持不变,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17758420/

10-14 21:33
查看更多