2015-06-09 79 views
0

我在表格視圖中有推薦歌曲的歌曲頁面。當用戶點擊推薦的歌曲時,我想用新數據重新加載歌曲頁面。要做到這一點,我用這個方法,從細胞到它自己的看法控制器賽格瑞:用新數據刷新相同的視圖控制器?

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方法做所有這些的最好方法是什麼?

+0

你想在'newSong'中傳遞什麼? – iDhaval

+0

@DhavalThanki recommendedTitles [indexPath.row] – chicobermuda

+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)!] 

    } 
} 
+0

當我通過recommendedTitles [indexPath.row]時,我將它傳遞給已經是字符串在viewDidLoad中聲明。我怎樣才能確保我傳遞的信息覆蓋了我在viewDidLoad中設置的內容? – chicobermuda

+0

你可以在'SongViewController'中聲明'搜索'變量的默認值'var search:String =「」'不要覆蓋'viewDidLoad'的值 – iDhaval

+0

那麼如何確保recommendedTitles [indexPath.row]作爲搜索變量覆蓋我手動設置它在viewDidLoad()? – chicobermuda

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 

     } 
    }