天天看點

UIStoryBoard中viewController之間的跳轉與傳值

UIStoryBoard中viewController之間的跳轉與segue

在使用storyboard中,三種segue類型:push、modal、custom。大多數情況會在UINavgationController控制器棧中使用push類型。通過segue可以實作不同視圖控制器之間的跳轉和傳值。

例如通過tableViewCell或者collectionViewCell連接配接segue到另一個storyboard中的viewController。然後在prepareForSegue:(UIStoryboardSegue *)segue sender:(id )sender方法中傳值。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id )sender
{
    NSLog(@"prepare segue");
    _mySegue = segue;
    if ([segue.identifier isEqualToString:@"showGift_topic"]) {
        HLGiftViewController *vc = segue.destinationViewController;
        vc.item_id = sender;

    }

}
           

今天遇到了另一種情況,不是由點選cell來觸發視圖切換,而是點選cell中的圖檔,觸發手勢事件來切換視圖,同時這兩個視圖控制器都是在storyboard中。

是以上面的方法就行不通了。這裡就需要用到另外一個方法performSegue。

1.首先選中VC1的viewController,拉出一個segue到VC2,segue類型可以設定為push、modal

2.在cell填充内容,給圖檔添加手勢事件。在這裡使用了block來做回調,block中調用

performSegue

方法。

[cell fillViewWithModel:item withBlock:^(NSNumber *item_id) {
     [self performSegueWithIdentifier:@"showGift_topic" sender:item_id];
 }];

- (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender{

    HLGiftViewController * giftVC = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"HLGiftViewController"];
    giftVC.item_id = sender;
    [self.navigationController pushViewController:giftVC animated:YES];
}
           

其中的重點在于如何擷取到要跳轉的目标視圖控制器,(不要試圖用

[[XXX alloc] init]

,這樣可以跳轉,但是沒有視圖)

[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]]

是用來擷取目前使用的storyboard的。而

instantiateViewControllerWithIdentifier

方法可以通過視圖控制器的storyboard identifier 來加載已經在storyboard上建立的viewController。(這裡不要和視圖控制器的class混淆)

UIStoryBoard中viewController之間的跳轉與傳值