点击TableView中某行进入下一级界面(Swift)

  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 - 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.dataController
objectInListAtIndex: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请网上查找下资料。

  

上一篇:git-ssh 配置和使用


下一篇:Log4j2在项目中的常用配置