iOSプロトコルの継承
今日pdfドキュメントを見て、プロトコルの継承を知りました.特に小さなdemoテストをしました.次はコードです.
OneDelegate.h
TwoDelegate.h
ViewController.h
ViewController.m
ViewController2.h
ViewController2.m
OneDelegate.h
@protocol OneDelegate <NSObject>
@required
- (void)backStr:(NSString *)str;
@end
TwoDelegate.h
@protocol TwoDelegate <OneDelegate>
@optional
- (void)backInt:(int)i;
@end
ViewController.h
#import "ViewController2.h"
@interface ViewController : UIViewController <TwoDelegate>
@end
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(50, 50, 200, 100);
button.backgroundColor = [UIColor yellowColor];
[button setTitle:@"into VC2" forState:UIControlStateNormal];
[button addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)push{
ViewController2 *vc = [[ViewController2 alloc]init];
vc.delegate = self;
[self presentViewController:vc animated:YES completion:^{
}];
}
//OneDelegate
- (void)backStr:(NSString *)str{
NSLog(@"%@",str);
}
//TwoDelegate
- (void)backInt:(int)i{
NSLog(@"%d",i);
}
ViewController2.h
#import <UIKit/UIKit.h>
#import "two.h"
@interface ViewController2 : UIViewController
@property(nonatomic ,unsafe_unretained)id delegate;
@end
ViewController2.m
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(50, 50, 200, 100);
button.backgroundColor = [UIColor yellowColor];
[button addTarget:self action:@selector(backStrBtn) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button2.frame = CGRectMake(50, 200, 200, 100);
button2.backgroundColor = [UIColor blueColor];
[button2 addTarget:self action:@selector(backIntBtn) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button2];
}
- (void)backStrBtn{
if (self.delegate && [self.delegate respondsToSelector:@selector(backStr:)]) {
[self.delegate backStr:@" 1 "];
}
}
- (void)backIntBtn{
if (self.delegate && [self.delegate respondsToSelector:@selector(backInt:)]) {
[self.delegate backInt:2];
NSLog(@" ");
}
}