ios - 使按钮在所有 View Controller 中持久化

标签 ios uiview uiviewcontroller uiwindow

我想在我的应用的右下角有一个固定按钮。在所有 View 转换期间,按钮应保持静态。我无法决定将按钮添加到哪个 View 。我知道按钮应该存储在 AppDelegate 中,但我不知道将它添加到除了窗口之外的其他 View 是有意义的。将其添加到窗口的一个缺点是,当有应用程序在后台运行时(即电话),添加的状态栏填充将下推窗口。一般来说,将它添加到窗口似乎是一个 hacky 解决方案——有什么想法吗?

最佳答案

是的,将它添加到 UIWindow 会非常棘手和挑剔。

Storyboard

如果您使用 Storyboards 和 iOS 5.0 以上版本,您应该能够使用容器 View 并执行如下操作:

MAH BUTTON IS PLEASED

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

enter image description here

左边的 View Controller 有一个容器,然后是一个在其顶部放置按钮的 View 。容器指示导航 Controller (直接向右)应出现在其自身内,该关系由 =([])=> 箭头(正式名称为 embed segue)。最后,导航 Controller 将其 Root View Controller 定义为右侧的那个。

总而言之,第一个 View Controller 煎饼 - 在容器 View 中,按钮在顶部,所以里面发生的一切都必须让按钮在顶部。

使用 childViewControllers

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

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

为了清楚起见,我们将持有按钮的一个 View Controller 称为 FakeRootViewController,并且出于所有实际目的,该 View Controller 将成为应用程序的根: Root View Controller 。所有后续的 View Controller 甚至都不知道在其他所有 View 之上有一个 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/

相关文章:

ios - 在 MVC 中绘制模型 View 或 Controller 的 UIBezierPath 部分

iphone - 在 AppDelegate 中调用时 subview 下移 20 像素

iOS Swift window.rootViewController 与 presentViewController

ios - UIViewController 的循环展示

ios - swift 错误 : Reference to generic type Dictionary requires arguments in <. ..>

ios - 通过 Cocoapods 设置 CVCalendar : Views Aren't Showing

ios - 绘制圆线iOS Swift

ios - 我在 UITableView 中添加了一个 View ,并且该 View 和第一个单元格之间存在间隙。我怎样才能删除它?

iOS:UIView 外的实心边框

swift - UICollectionView 行为与 Subview 不同