您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 教學:ViewController 跳轉與傳值(方式一)

編輯:iOS 開發綜合

方式一:透過定義一個實體類來傳值(從 ViewController1 跳轉至 ViewController2)。

1、定義實體類 NotificationEntity

.h 宣告檔:

#import <Foundation/Foundation.h>

@interface NotificationEntity : NSObject
{
}
@property (nonatomic,retain) NSString *strTitle;   // 參數一
@property (nonatomic,retain) NSString *strContent; // 參數二
@property (nonatomic,retain) NSString *strUrl;     // 參數三
@end

.m 實作檔:

#import "NotificationEntity.h"

@implementation NotificationEntity
@synthesize strTitle = _strTitle;
@synthesize strContent = _strContent;
@synthesize strUrl = _strUrl;
@end

2、在 ViewController2 中宣告成員變數

在 .h 中將 NotificationEntity 宣告為類成員變數:

@property (retain,nonatomic) NotificationEntity *mNotifEntity;

在 .m 中合成存取方法:

@synthesize mNotifEntity = _mNotifEntity;

3、在 ViewController1 中實現跳轉並傳參

// 組裝實體類的實例變量
NotificationEntity *mNotificationEntity = [[NotificationEntity alloc] init];
[mNotificationEntity setStrTitle:strTitle];
[mNotificationEntity setStrContent:strContent];
[mNotificationEntity setStrUrl:strUrl];
// 實例化 ViewController2
ViewController2 *viewController2 = [[ViewController2 alloc] init];
// 注入參數
[viewController2 setMNotifEntity:mNotificationEntity];
// 跳轉
[self.window.rootViewController presentModalViewController:viewController2 animated:YES];

4、在 ViewController2 中接收參數

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.lblTitle setText:[self.mNotifEntity strTitle]];
    [self.lblContent setText:[self.mNotifEntity strContent]];
}

5、加入返回 ViewController1 的事件

- (IBAction)backOff:(id)sender {
    [self dismissModalViewControllerAnimated:YES];
}

如此一來,透過實體類即可在兩個 ViewController 之間完成資料的傳遞與回傳。

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