将索引行传递给另一个视图

时间:2015-11-09 15:29:21

标签: ios swift uitableview

在我的UItableView中,我希望传递给SecondViewController Row索引。 问题是:  prepareForSegue是在didSelectRowAtIndexPath之后调用的,因此screenNumber的结果是" nil"

表:

 class ViewController: UITableViewController{
        var FirstTableArray = [String]()
        var nextScreenRow: NSInteger?

        override func viewDidLoad() {
            super.viewDidLoad()
            FirstTableArray = ["first","second","third"]
        }
        override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return FirstTableArray.count
        }
        override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            tableView.deselectRowAtIndexPath(indexPath, animated: true)
            var Cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

            Cell.textLabel?.text = FirstTableArray[indexPath.row]

            return Cell
        }

        override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
            nextScreenRow = indexPath.row

        }

        override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

            if (segue.identifier == "Cell") {

                println("nextScreenRow")

                var detailController = segue.destinationViewController as SecondViewController;

                detailController.screenNumber = nextScreenRow

            }
         }
    }

SecondViewController

class SecondViewController: UIViewController {

    var screenNumber: NSInteger!

    override func viewDidLoad() {
        super.viewDidLoad()  
        println("screenNumber")

    }
}

修改

  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

        if (segue.identifier == "Cell") {


            var detailController = segue.destinationViewController as SecondViewController;

            if let ip = tableView.indexPathForSelectedRow { //ERROR

                detailController.screenNumber = ip.row //ERROR
            }

        }


    }

1 个答案:

答案 0 :(得分:2)

您不需要在didSelectRowAtIndexPathprepareForSegue对象indexPathForSelectedRowtableView覆盖... if let ip = tableView.indexPathForSelectedRow { ... detailController.screenNumber = ip.row } ...

tableView.indexPathForSelectedRow()?.row

对于Swift 1.2使用:

object Model  {
    var gameData:Option[GameData] = None
    val data = new ObjectProperty(this,"data",Model.gameData)
    ...
}