使用新数据刷新相同的视图控制器?

时间:2015-06-09 06:44:43

标签: ios uitableview swift

我在表格视图中有一个推荐歌曲的歌曲页面。当用户点击推荐的歌曲时,我想基本上用新数据重新加载歌曲页面。要做到这一点,我正在使用这种方法,从单元格到它自己的视图控制器的segue:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        let newSong = recommendedTitles[indexPath.row]

        self.performSegueWithIdentifier("refreshSong", sender: newSong)

    }

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

        if segue.identifier == "refreshSong" {
            let newSong:String = sender as! String
            let song = segue.destinationViewController as! SongViewController
            song.search = newSong

        }
    }

但我在let newSong:String = sender as! String收到错误,could not cast value of type recommendationCell to NSString。使用上述tableView方法完成所有这些操作的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

您不必声明全局变量。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    self.performSegueWithIdentifier("refreshSong", sender: self)

}

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

    if segue.identifier == "refreshSong" {
        let indexPath = tableView.indexPathForSelectedRow()
        let song = segue.destinationViewController as! SongViewController
        song.search = recommendedTitles[(indexPath?.row)!]

    }
}

答案 1 :(得分:0)

你试试这个。在声明部分中取变量newSong

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        newSong = recommendedTitles[indexPath.row]

        self.performSegueWithIdentifier("refreshSong", sender: nil)

    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if segue.identifier == "refreshSong" {
            let song = segue.destinationViewController as! SongViewController
            song.search = newSong

        }
    }