ios - 创建类似于扩展 Swift 的 UIViewController 类别 (Obj-C)

标签 ios objective-c iphone uiviewcontroller objective-c-category

我正在尝试使用一些自定义方法来扩展标准 UIViewController

#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 继承自定义 View Controller 。

最佳答案

创建一个文件“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>

@interface SampleViewController : UIViewController
@end

然后在“SampleViewController.m”中:

#import "SampleViewController.h"
#import "UIViewController+Alert.h"

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

关于ios - 创建类似于扩展 Swift 的 UIViewController 类别 (Obj-C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46217694/

相关文章:

ios - 在ios sdk中获取当月星期一的所有日期

ios - @Binding var a : Int and Binding<Int> in SwiftUI? 之间的区别

ios - 应用委托(delegate) : unrecognised selector sent to instance

ios - 如何修复错误 : "Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffee0761ed8)"

ios - Apple Watch Extension 如何访问 NSDocumentDirectory 中的文件?

ios - 从 NSString 中删除空格后的字符

ios - 搜索处于事件状态时 didSelectRowAt indexPath 函数不起作用

iphone - 如何将 CGPoint 添加到 NSMutableArray?

iphone - 翻转 View iPhone

ios - 具有单击和长按事件的 UIButton swift