創建一個超類來抽象註銷行爲。然後,支持註銷的每個UIViewController應該繼承該超類。在超類中,提供註銷的方法。
這種方法可以使您簡單地將Interface Builder中的UIControls連接到超類中的公共IBAction,或者甚至在調用超類方法之前在子類中添加特定的自定義。
這裏有一個可能的例子:
LogoutViewController.h
#import <UIKit/UIKit.h>
@interface LogoutViewController : UIViewController
-(void)performLogout;
@end
LogoutViewController.m
#import "LogoutViewController.h"
@interface LogoutViewController()
@end
@implementation LogoutViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)performLogout
{
//do logout code
}
- (IBAction)logout:(id)sender
{
[self performLogout];
}
@end
SomeOtherViewController.h
#import <UIKit/UIKit.h>
#import "LogoutViewController.h"
@interface SomeOtherViewController : LogoutViewController
@end
SomeOthe rViewController.m
#import "SomeOtherViewController.h"
@implementation SomeOtherViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (IBAction)mySpecificLogoutButtonPressed:(id)sender
{
self.title = @"Good bye";
// do other code specific to logging out from this UIVC
[super performLogout];
}
@end
爲什麼所有那些UIViewControllers必須知道這種註銷行爲?有沒有辦法讓我有一個註銷按鈕的視圖,並有一個控制器處理所有內容,並簡單地將其作爲視圖的一部分?這似乎是更多面向對象的方式 – praks5432
我不同意這種方法更面向對象。在我提出的解決方案中,每個支持註銷的UIViewController都是通過超類定義的。話雖如此,如果你真的想採取你的方法,調查UIViewController遏制API。我不認爲這適合這種用例,因爲註銷按鈕很可能控制屏幕上的全部UIView,而不僅僅是屏幕的一小部分。 –