まだObjective-Cなんかやってんのかよーという声も聞こえてきそうですが、
Objective-CでSegueを使って遷移する時に超便利なカテゴリーを今回は紹介します!
UIViewController+SegueBlock.h
#import <UIKit/UIKit.h>
typedef void (^SegueBlock) (UIStoryboardSegue *segue);
@interface UIViewController (SegueBlock)
- (void)performSegueWithIdentifier:(NSString *)segue sender:(id)sender block:(SegueBlock)block;
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender NS_REQUIRES_SUPER;
@end
UIViewController+SegueBlock.m
#import "UIViewController+SegueBlock.h"
#import <objc/runtime.h>
@implementation UIViewController (SegueBlock)
- (void)performSegueWithIdentifier:(NSString *)segue sender:(id)sender block:(SegueBlock)block
{
objc_setAssociatedObject(self, _cmd, block, OBJC_ASSOCIATION_RETAIN);
[self performSegueWithIdentifier:segue sender:sender];
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender NS_REQUIRES_SUPER
{
if ([self segueBlock]) {
[self segueBlock] (segue);
}
objc_setAssociatedObject(self, @selector(performSegueWithIdentifier:sender:block:), nil, OBJC_ASSOCIATION_RETAIN);
}
#pragma clang diagnostic pop
- (SegueBlock)segueBlock
{
return objc_getAssociatedObject(self, @selector(performSegueWithIdentifier:sender:block:));
}
@end
使用例
ViewController.m
- (IBAction)showSecondViewControllerButton:(UIButton *)sender {
[self performSegueWithIdentifier:@"showSecondViewControler" sender:nil block:^(UIStoryboardSegue *segue) {
SecondViewController *secondViewController =segue.destinationViewController;
secondViewController.labelText = @"segueのブロックで値渡し";
}];
}
// 以下のメソッドを実装する場合は Super でメソッドを呼ぶ
//- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
//{
// [super prepareForSegue:segue sender:sender];
//}
@end
ブロックでdestinationViewControllerを取得できるので
次のViewControllerに値やオブジェクトを渡す時にかなり便利になります!
Githubにソースコードを上げてます。
SegueSample-GitHub