StoryBoard初探(三):自定義Segue以及頁面間傳值

自定義Segue

StoryBoard三種連接中,有一種類型是Custom,開發者可以使用自定義的Segue,自定義Segue類需要繼承類UIStoryBoardSegue,並重寫perform方法:
- (void)perform
{
    NSLog(@"使用自定義連接");
    [self.sourceViewController presentViewController:self.destinationViewController animated:YES completion:nil];
}

Ctrl連線ViewController的按鈕到ViewController2,並選擇Segue類型爲Custom,點擊連接,並將連接的類別設置爲剛剛自定義的PresentSegue。


運行效果和直接使用Modal類型連接效果一樣:

當然也可以自定義Push類型的連接

頁面傳值

如果希望頁面之間的內容有所關聯,則需要實現頁面間傳值,在StoryBoard中,頁面傳值是通過prepareForSegue:sender:方法實現。先設置連接的Identifier爲2vc2(可以根據自己的需要命名,保持跟代碼中的字符串一致就OK)

拖拽一個UITextView實例到頁面2上,並關聯輸出口recTextView



在ViewController.m中添加如下代碼:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"2vc2"]) {
        ViewController2 *vc2 = (ViewController2 *)[segue destinationViewController];
        vc2.passText = @"使用prepareForSegue:sender進行頁面傳值";
    }
}
在ViewController2.m中把passText的值賦給recTextView.text
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _recTextView.text = _passText;
}

模擬器運行:





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章