2014-12-01 103 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