1

我试图用一些自定义方法扩展标准UIViewControllerUIViewController扩展

#import <UIKit/UIKit.h> 

@interface UIViewController (UIViewControllerExtension) 
- (void) showNoHandlerAlertWithTitle:(NSString *)title andMessage:  (NSString*)message; 
- (void) showAlertWithTitle:(NSString *)title andMessage:(NSString*)message buttonTitles:(NSArray<NSString *>*)titles andHandler:(void (^)(UIAlertAction * action))handler; 
@end 

如何现在可以使用扩展UIViewController?我需要从扩展UIViewController继承我的自定义视图控制器。

+2

把你的代码放在这里不是图像的代码 –

+0

这是一个类,对吧?然后,只需在UIViewController子类对象上导入.h文件。 – Larme

+0

将.h文件导入到我的自定义视图控制器不起作用。扩展方法不可用。 – user267140

回答

1

创建一个包含文件 “的UIViewController + Alert.h”:

#import <UIKit/UIKit.h> 
@interface UIViewController (AlertExtension) 
- (void) showNoHandlerAlertWithTitle:(NSString *)title andMessage:  (NSString*)message; 
- (void) showAlertWithTitle:(NSString *)title andMessage:(NSString*)message buttonTitles:(NSArray<NSString *>*)titles andHandler:(void (^)(UIAlertAction * action))handler; 
@end 

然后,创建一个文件,其中包含 “的UIViewController + Alert.m”:

#import "UIViewController+Alert.h" 
@implementation UIViewController (AlertExtension) 
- (void) showNoHandlerAlertWithTitle:(NSString *)title andMessage:  (NSString*)message { 
    // Insert code here 
} 

- (void) showAlertWithTitle:(NSString *)title andMessage:(NSString*)message buttonTitles:(NSArray<NSString *>*)titles andHandler:(void (^)(UIAlertAction * action))handler { 
    // Insert code here 
} 
@end 

在说你的“SampleViewController .H“:

#import <UIKit/UIKit.h> 
#import "UIViewController+Alert.h" 

@interface SampleViewController : UIViewController 
@end 

然后在 ”SampleViewController.m“:

#import "SampleViewController.h" 
@implementation SampleViewController 
- (void)viewDidLoad { 
    [super viewDidLoad]; 
    [self showNoHandlerAlertWithTitle:@"Hello" andMessage:@"World"]; 
} 
@end 

享受!

+1

在实现中导入'UIViewController + Alert.h'就足够了,否则你会污染你的头文件。 '@import UIKit;'现在应该优先于'#import '。 – Sulthan

+0

没有更多关于哪个版本的Xcode以及在其构建设置中是否将“启用模块”设置为YES的更多上下文,请使用@import UIKit;实际上可能导致他的代码不能编译;我更喜欢谨慎的继承人,并重新使用问题中使用的类似语法。话虽如此,除非您的代码的其他部分能够在您的视图控制器上使用这些功能,否则您完全可以在实现中导入UIViewController + Alert.h! – ekscrypto

相关问题