TableView這個控件在iOS的開發中非常的常見,他可以較好的展示一個層級結構。這里主要介紹,在點擊某個條目的時候,如何進行跳轉的下一個界面。以下是官方的關于這個跳轉如何去實現,和如何去傳遞數據的過程。
Storyboards make it easy to pass data from one scene to another via the PRepareForSegue:sender: method of the UIViewController class. This method is called when the first scene (the source) is about to transition to the next scene (the destination). The source view controller can implement prepareForSegue:sender: to perform setup tasks, such as passing information to the destination view controller about what it should display in its table view. Listing 3-1 shows one implementation of this method.
Storyboards利用func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!)將數據從一個界面傳輸到另外一個界面。這個函數在源界面切換到目標界面的時候會調用。所以在源View Controller中可以重載func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!)這個方法,在該方法內完成將數據傳送到目的View Controller。下面就是這個函數一般的實現方式。
(Objective-C)
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{if ([[segue identifier] isEqualToString:@"ShowDetails"]) { MyDetailViewController *detailViewController = [segue destinationViewController]; NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; detailViewController.data = [self.dataControllerobjectInListAtIndex:indexPath.row];} }
(Swift)
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if(segue.identifier == "ShowDetails"){
var detailViewController:MyDetailViewController ! = segue.destinationViewController as MyDetailViewController
var index = tableView.indexPathForSelectedRow()
detailViewController.data = dataController[index!.row]
}
}
A segue represents a one-way transition from a source scene to a destination scene. One of the consequences of this design is that you can use a segue to pass data to a destination, but you can’t use a segue to send data from a destination to its source. To solve this problem, you create a delegate protocol that declares methods that the destination view controller calls when it needs to pass back some data.
Segue是條從源界面到目標界面的一條路。你可以通過Segue將數據從源界面->目標界面。
以上的過程是在tableViewCell與DetailView界面建立Segue連接的情況下,并且設置了Segue的identifer。
Segue是完全在Storyboard可以拖拽建立,比較簡單,關于如何建立Segue請網上查找下資料。
新聞熱點
疑難解答