【问题标题】:wrong code for UITableview SWIFTUITableview SWIFT 的错误代码
【发布时间】:2014-12-01 19:23:56
【问题描述】:

主要作用是在表格视图中显示播放列表名称,但它在大约 500 个单元格中显示单词“名称”!

我可以犯一个简单的错误,因为我只学习 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")
}
}

【问题讨论】:

  • 您不会根据索引路径为单元格设置不同的文本。

标签: iphone xcode uitableview swift audio-player


【解决方案1】:

您的问题是您在单元格中显示 MPMediaPlaylistPropertyName,这很可能只是常量字符串“name”

您需要做的是使用播放列表的实际名称设置单元格的 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;

此外,您需要确保从 tableData 的集合中获取计数,以便更改 rowsInSectionMethod 的数量:

return self.tableData.items.count

return self.tableData.collections.count

为了进一步理解,我们现在在 cellForRowAtIndexPath 中所做的是:

  1. 获取特定行的特定 MPMediaPlaylist 项
  2. 获取播放列表的名称并将其分配给变量
  3. 将该名称分配给单元格 textLabel

如果您有任何其他问题,请告诉我

【讨论】:

  • 这几乎可以工作了!总共有 22 个单元格,但它们是空的(没有名称)
  • 你确定你有我发布的最新代码吗?我编辑了几次
  • 糟糕!对不起,我只是忘了添加 cell.textlable !现在可以工作了,非常感谢!
【解决方案2】:

您必须清理单元格数据,因为您正在重复使用单元格, 就在一行之后

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

cell.textLabel.text = ""

【讨论】:

  • 重置单元格数据的地方在+prepareForReuse方法中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多