你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS 協議的繼承

iOS 協議的繼承

編輯:IOS開發綜合

今天看了一個pdf文檔,了解到了 協議的繼承,特別做了個小demo測試了一下,下面是代碼


OneDelegate.h

@protocol OneDelegate 

@required

- (void)backStr:(NSString *)str;

@end


TwoDelegate.h

@protocol TwoDelegate 

@optional

- (void)backInt:(int)i;

@end

ViewController.h

#import "ViewController2.h"

@interface ViewController : UIViewController 

@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 
#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(@"這是繼承的方法");
    }
}


  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved