您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 中用代理(Delegate)實現頁面反向傳值

編輯:iOS 相關資訊

應用場景:有時候從介面 A 跳轉到介面 B,當介面 B 返回時,需要將處理的結果回傳給介面 A。這時就可以透過代理來實現反向傳值。

實現思路

1、定義一個負責傳值的協議(protocol),介面 A 擁有該協議的屬性並實作協議中的方法;
2、介面 B 同樣持有該協議屬性(代理要求雙方都引用同一個物件),在返回時取得介面 A 的引用指標,將 B 中協議的呼叫目標設為 A,再呼叫協議中的傳值方法。

介面 A 的頭檔案

#import <UIKit/UIKit.h>

@protocol PassValueDelegate <NSObject>
- (void)setValue:(NSString *)param;
@end

@interface ViewController : UIViewController
@property (id<PassValueDelegate>) passValueDelegate;
@end

介面 A 的實現檔案

#import "ViewController.h"
#import "ViewController2.h"

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(100, 100, 200, 40);
    [btn setTitle:@"btn" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    self.view.backgroundColor = [UIColor redColor];
}

- (void)setValue:(NSString *)param {
    NSLog(@"pass value is:%@", param);
}

- (void)btn
{
    [self.navigationController pushViewController:[[ViewController2 alloc] init] animated:YES];
}
@end

介面 B 的實現檔案

介面 B 在私有類別延伸中持有代理屬性,並在返回時將自身 delegate 指向導航堆疊中的 A:

#import "ViewController2.h"
#import "ViewController.h"

@interface ViewController2 ()
@property (id<PassValueDelegate>) passValueDelegate;
@end

@implementation ViewController2

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(100, 100, 200, 40);
    [btn setTitle:@"back" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

- (void)btn
{
    self.passValueDelegate = self.navigationController.childViewControllers[0];
    [self.navigationController popToRootViewControllerAnimated:YES];
    [self.passValueDelegate setValue:@"123456789"];
}
@end

透過這種代理機制,介面 B 便能在返回前把結果回傳給介面 A,實現頁面的反向資料傳遞。

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