假設有兩個 View,分別為 FirstViewcontroller、SecondViewController,
若我們想將 FirestViewController 的值傳給 SecondViewController 的話那該怎麼做呢?
首先,要先將兩個 ViewController 建立關係,
在 FirstViewController 建立一個 button 連結到 SecondViewController,選擇 Modal
新增一個字串(因為這個字串要提供給 self class 以外的類別使用,所以要在 .h 檔宣告):
@property (strong, nonatomic) NSString *strInFirstVC;
_strInFirstVC = [NSString stringWithFormat:@"這是在 FirstVC 的一個字串"];
SecondViewController 也新增一個:
@property (strong, nonatomic) NSString *strInSecondVC;
然後在 FirstViewController 新增以下 method 進行傳值:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
id targetViewController = segue.destinationViewController;
[targetViewController setValue:_strInFirstVC forKey:@"strInSecondVC"];
}
為了證明傳值成功,
我們在 SecondViewController 將字串列印出來
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"這是第二個 VC");
NSLog(@"%@", _strInSecondVC);
}
執行模擬器,按下 button,若成功切換到 SecondViewController 並且顯示:
則表示我們成功了!!
