prepareForSegue 方法会调用两次的问题

    //  UITableViewDelegate 方法,处理列表项的选中事件
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        let identifier = imagesOfCersonalInfoCells[indexPath.row]
        let cellName = lableNamesOfCersonalInfoCells[indexPath.row]

        self.performSegueWithIdentifier(identifier+"Segue", sender: cellName)
    }

    // 在这个方法中给新页面传递参数
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
    {
        let segueName = segue.identifier
        let controller = segue.destinationViewController as! UIViewController // 有多个view, 都是UIViewController的子类
        controller.title = sender as? String
    }

这里找到了答案

The problem is prepareForSegue is called before didSelectRowAtIndexPath. You should just eliminate the didSelectRowAtIndexPath method, and do everything in prepareForSegue. You can use the following line to get the indexPath you need:

NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

将上面的代码修改为:

 //  UITableViewDelegate 方法,处理列表项的选中事件
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        // do nothing
    }

    // 在这个方法中给新页面传递参数
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
    {
        let segueName = segue.identifier
        // 选中的行
        let selectedRowIndex = self.personalInfoTableView.indexPathForSelectedRow()?.row
        let controller = segue.destinationViewController as! UIViewController // 有多个view, 都是UIViewController的子类
        // 取选中行的labelname, 设置目标controller的title
        controller.title = lableNamesOfCersonalInfoCells[selectedRowIndex!]
    }

当然,这里的前提是已经为 tableView 中的 cell 设置了 segue, 为 cell 设置了 segue, 就会跳转到指向的目标, 如果再在didSelectRowAtIndexPath中跳转, 自然就会跳转了两次.

如果没有为 cell 设置 segue, 而是把 segue 设置在tableView所在的 viewController上, 那么需要通过performSegueWithIdentifier 再一次跳转.

2015-06-28 15:2157