ios - 如何让一个按钮在 iOS 的每个屏幕上做同样的事情?

标签 ios uiviewcontroller

我的应用程序每个屏幕的工具栏(通过 Storyboard制作)中都有一个“注销”按钮。无论点击哪个页面,我都希望它执行相同的操作。

有没有办法让所有这些按钮做同样的事情,而不必在每个 View Controller 中创建相同的 IBAction 方法(我有一堆不同类型的 View Controller )?

最佳答案

一种解决方案是在所有工具栏上共享该按钮。这既丑陋又困难。我的偏好是将注销逻辑封装在它自己的类中,然后从所有按钮调用它:

#import "AccountManager.h"

@implementation AccountManager

+ (id)sharedManager
{
    static AccountManager *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[AccountManager alloc] init];
    });

    return sharedManager;
}

- (void)logout
{
    // logout logic
}

@end

然后在你的 View Controller 中你可以拥有

#import "AccountManager.h"

- (IBAction)didSelectLogout:(id)sender
{
    [[AccountManager sharedManager] logout];
}

在这种情况下,您仍然在每个 Controller 中都有一个操作,但您的注销逻辑不会分布在整个应用程序中。

关于ios - 如何让一个按钮在 iOS 的每个屏幕上做同样的事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10656294/

相关文章:

ios - [UIImageView CGImage] : unrecognized selector sent to instance 0x1783e5b00

ios - 在代码中更改框架后自动布局重置 View

objective-c - 在导航 Controller 中推送 UIViewController 显示空 View

iOS7 崩溃 - PopViewController 在 Landscape ViewController 上调用

ios - Swift 在代码中将方向设置为特定屏幕

iOS SDK : How to cause view to flip when switching cameras

ios - UIPopoverPresentationController 动画 preferredContentSize

ios - 上面的 UITabBarItem 图像而不是文本旁边

iphone - 如何在 iPhone 中创建登录屏幕(作为 UIAlertView)?

ios - UIView 和 UIViewController 设计模式