2014-12-01 101 views
0

主要作用是在表格視圖中顯示播放列表名稱,但它在約500個單元格中顯示單詞「名稱」!UITableview的錯誤代碼SWIFT

我可以做一個簡單的錯誤,因爲我只學習迅速,這是我的第一個編程語言

有代碼:

import UIKit 
import MediaPlayer 

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

@IBOutlet var tableView: UITableView! 

var tableData = MPMediaQuery.playlistsQuery() 
var songname: NSString = MPMediaPlaylistPropertyName 

override func viewDidLoad() { 
    super.viewDidLoad() 


    self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") 

    self.tableView.reloadData() 

} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return self.tableData.items.count 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell  { 

    var cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell 

    cell.textLabel.text = songname 

    return cell 
} 

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { 
    println("Row \(indexPath.row) selected") 
} 
} 
+0

您沒有設置取決於索引路徑,單元格的不同文本。 – Abizern 2014-12-01 20:08:39

回答

0

你的問題是,你在其中是最有可能只是字符串常量「名稱」單元格顯示MPMediaPlaylistPropertyName

你需要做的是設置單元格的爲textLabel與播放列表的實際名稱是什麼,其會是這個樣子在你的cellForRowAtIndexPath方法

更換

cell.textLabel.text = songname 

隨着

let playlist: MPMediaPlaylist = tableData.collections[indexPath.row] as MPMediaPlaylist 
let playlistName = playlist.valueForProperty(MPMediaPlaylistPropertyName) as NSString 
cell.textLabel.text = playlistName; 

另外,你需要確保你得到從表資料的館藏數量,使得在rowsInSectionMethod變化的數字:

return self.tableData.items.count 

return self.tableData.collections.count 

對於多一點理解,我們現在在cellForRowAtIndexPath中所做的是:

  1. 爲此獲取特定的MPMediaPlaylist項目特定的行
  2. 獲取播放列表的名稱,並將其賦值給一個變量
  3. 爲textLabel
  4. 分配該名稱到細胞

讓我知道,如果您有任何其他疑問

+0

這幾乎是現在的工作! 22個單元格應該是完整的,但它們是emty(沒有名字) – 2014-12-01 20:47:29

+0

你確定你已經獲得了我發佈的最新代碼嗎?我編了幾遍 – 2014-12-01 20:48:45

+0

哎呀!對不起,我忘了添加cell.textlable!現在它是工作,謝謝你很多! – 2014-12-01 20:50:55

-2

,因爲你是你必須清理單元格數據重複使用的電池, 行後右

var cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell 

cell.textLabel.text = "" 
+0

重置單元格數據的位置在'+ prepareForReuse'方法中。 – Abizern 2014-12-01 20:07:10