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

iOS 委派(Delegate)協定用法(二):頁面間回傳值

編輯:iOS 相關資訊

委派的核心觀念:ShowViewController 需要從被彈出的 PopViewController 取回資料。關鍵在於必須正確設定代理(delegate)——就像你若沒有委託某人替你辦事,對方自然不會理你一樣。

(1)PopViewController.h:定義協定

#import <UIKit/UIKit.h>

// 定義協定
@protocol popNextDelegate <NSObject>
-(void)passPopReport:(NSString *)string;
@end

@interface PopViewController : UIViewController
@property(nonatomic, retain) NSObject <popNextDelegate> *popDelegate; // 聲明一個代理
- (IBAction)reportAction:(UIButton *)sender;
@end

(2)PopViewController.m:透過代理回傳值

- (IBAction)reportAction:(UIButton *)sender {
    [self.popDelegate passPopReport:@"檢舉"]; // 賦值並回傳
}

(3)ShowViewController.h:遵守協定

@interface ShowViewController : UIViewController <iCarouselDataSource, iCarouselDelegate, UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate, popNextDelegate>{
    UIView *moreView;
}

(4)ShowViewController.m:實作協定方法(接收值)

-(void)passPopReport:(NSString *)string {
    if ([string isEqualToString:@"檢舉"]) {
        ReportViewController *report = [[ReportViewController alloc] init];
        [self.navigationController pushViewController:report animated:YES];
    }
}

(5)ShowViewController.m:設定 delegate

-(void)pop:(id)sender {
    PopViewController *pop = [[PopViewController alloc] init];
    pop.popDelegate = self; // 誰實作了 delegate 方法就指定給誰
    FPPopoverController *basePop = [[FPPopoverController alloc] initWithViewController:pop];
    basePop.tint = FPPopoverLightGrayTint;
    basePop.arrowDirection = FPPopoverArrowDirectionAny;
    [basePop presentPopoverFromView:sender];
}

透過以上五個步驟,被呈現的控制器便能在使用者操作後,把資料回傳給呼叫它的源控制器,這是 iOS 中非常典型的委派傳值模式。

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